Problema na hora do printf em C

Está imprimindo coisas aleatórias no printf..

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>

typedef struct 
 {
   char nome(50);
   char cargo(50);
   char endereco(100);
   char cpf(11);
   int idade;
   int salario;
 } Funcionario;
Funcionario func(2);

 int main()
 {
  int i;
  setlocale(LC_ALL,"portuguese");
  Funcionario soma;
  soma.salario= func(1).salario + func(2).salario;
  for(i=0; i<2; i++) {
    strcpy(func(i).nome, "NULL");
    strcpy(func(i).cargo, "NULL");
    strcpy(func(i).endereco, "NULL");
    strcpy(func(i).cpf, "NULL");
    func(i).idade = 0;
    func(i).salario = 0;
  }
  for(i=0; i<2; i++) {
    printf("nNome do funcionario: ");
    scanf("%s", &func(i).nome);
    printf("Cargo: ");
    scanf("%s", &func(i).cargo);
    printf("Endereco: ");
    scanf("%s", &func(i).endereco);
    printf("CPF: ");
    scanf("%s", &func(i).cpf);
    printf("Idade: ");
    scanf("%d", &func(i).idade);
    printf("Salario: ");
    scanf("%d", &func(i).salario);
    printf("nFuncionario registrado com sucesso!n");
  }
    printf("nNome e salario de todos funcionario:nn%s: %dn%s: %dn%s: %dn%s: %dn%s: %dnnTotal: %d", func(1).nome, func(1).salario, func(2).nome, func(2).salario, soma.salario);
}

printf – Não estou conseguindo compilar C++

      #include <stdio.h>
      #include <stdlib.h>
      int main (void);
    {
      int n1=10;

      printf(¨valor de n1=%d n¨,n1);
      system (pause);//pausa da tela somente para windows
      return (0);//voltar ao retorno da funcao main
    }



system (pause);//pausa da tela somente para windows
return (0);//voltar ao retorno da funcao main
}

c – padding in printf (float)

i want to display in the title bar of an emulator the name, speed% and frame rate, something like

100.00% 50.000fps

the problem is, speed usually is either slightly below or above 100%, making it jumping left and right.

i know i can do padding “zeros”

“%s at %05.2f%% speed, %05.3f fps”

but a leading zero (like 099.89%) looks really stupid.

also, the default padding with spaces does not help, as obviously a space doesn’t have the same with as a digit, so it jumps too.

is this even possible (without using some fixed (monospace) font)?

linux – Setting “LANG=C LC_ALL=C” in script has no effect on padding length for non-English characters in printf

I am working on formatting the output of a Bash script into a table such that the pipe characters used to represent the bounds of each column are spaced relative to the longest string in that column (thus lining up all of the pipe characters nicely).

Below is the relevant bit of output. Note how both for the “il2” and “ksp” rows, both pipe characters are aligned, however in the “iceland” row, which contains the non-English character ‘ý’, the second pipe character is left-indented one space relative to the other rows.

iceland          | Mýrdalssandur Iceland                    | steam://rungameid/1248990                                                                   | iceland-Win64-Shipping.exe
il2              | IL 2 Sturmovik: 1946                      | steam://rungameid/15320                                                                     | il2fb.exe
ksp              | Kerbal Space Program                      | steam://rungameid/220200                                                                    | KSP_x64.exe

At the very beginning of the script, I have the following:

oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C

And at the end, right before the final “done” statement, I have:

LANG=$oLang LC_ALL=$oLcAll

There is no other change of language settings throughout the script.

If in a shell I set a $string variable to “Mýrdalssandur Iceland” and run printf "%-14s is %2d char lengthn" "'$string'" ${#string}, I get a character length of 21, but when I run LANG=C LC_ALL=C and then printf "%-14s is %2d char lengthn" "'$string'" ${#string}, I get a character length of 22, showing that it should in-fact make a difference.

I created a barebones script to test the padding, and in that script, changing LANG does have the desired effect, even when the printf lines are contained in a function as they are in the main script in question.

I’m at a loss at this point as to why the output isn’t applying the language change, so any help is appreciated.

Here is the full script:

#!/bin/bash

oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C

#Config file location
listpath="/home/$USER/.config/play/"
config="$listpath"config
games="$listpath"games.list

if ! ( -f $config ) ; then
    echo "Config file not found at "$config""
    exit
fi

#Vars/arrs used for script
gamecmd="$1"
prgm=""
line=""
pathf=""
ctr=0
rctr=0
appID=0
taskname=""
result=""
task=""
answer=""
longestshort=0
longestlong=0
longestpathf=0
longestservicename=0
ip=`cat $config | sed -n -e 's/^.*ip=//p'`
wr=`cat $config | sed -n -e 's/^.*wr=//p'`
display=`cat $config | sed -n -e 's/^.*display=//p'`
ControlMyMonitor=`cat $config | sed -n -e 's/^.*ControlMyMonitor=//p'`
ControlMyMonitor=${ControlMyMonitor//\//}
declare -a short
declare -a long
declare -a path
declare -a servicename

#Shortcut locations to make adding games easier
STEAM="steam://rungameid/"
DESKTOP=`cat $config | sed -n -e 's/^.*desktop=//p'`
APPDATA=`cat $config | sed -n -e 's/^.*appdata=//p'`

function check_for_duplicate()
{
    dctr=0

    #Set delimiter to comma
    IFS=','

    while IFS= read -r line
    do
        read -a strarr <<< "$line"

        for (( n=0; n < ${#strarr(*)}; n++))
        do
            if ( "${strarr(n)}" == "$1" )
            then
                get_record $dctr "$line"
                echo -e "Duplicate entry for ""$1"" found:"
                echo
                print_verbose_header
                echo
                pathf="${path($dctr)}"
                format_pathf
                    print_verbose_record "${short($dctr)}" "${long($dctr)}" "$pathf" "${servicename($dctr)}"

                exit
            fi
        done
        ((dctr++))
    done < $games
}
function format_pathf()
{
    pathf="${pathf//"/}"
    pathf="${pathf//%STEAM%/$STEAM}"
    pathf="${pathf//%DESKTOP%/$DESKTOP}"
    pathf="${pathf//%APPDATA%/$APPDATA}"
}
function get_normal_header_spacing()
{
    for (( IFS=" " i=0; i<$ctr; i++ ))
    do
        if ( "${#short(i)}" -gt "$longestshort" )
        then
            longestshort="${#short(i)}"
        fi
        if ( "${#long(i)}" -gt "$longestlong" )
        then
            longestlong="${#long(i)}"
        fi
        done
}
function get_verbose_header_spacing()
{
    for (( IFS=" " i=0; i<$ctr; i++ ))
    do
        if ( "${#short(i)}" -gt "$longestshort" )
        then
            longestshort="${#short(i)}"
        fi
        if ( "${#long(i)}" -gt "$longestlong" )
        then
            longestlong="${#long(i)}"
        fi

        pathf="${path(i)}"
        format_pathf

        if ( "${#pathf}" -gt "$longestpathf" )
        then
            longestpathf="${#pathf}"
        fi
        if ( "${#servicename(i)}" -gt "$longestservicename" )
        then
            longestservicename="${#servicename(i)}"
        fi
        done
}
function get_record()
{
    short($1)=$(echo "$2" | grep -Po '((^,)+)' | head -1)
    long($1)=$(echo "$2" | grep -Po '((^,)+)' | head -2 | tail -1)
    path($1)=$(echo "$2" | grep -Po '((^,)+)' | head -3 | tail -1)
    servicename($1)=$(echo "$2" | grep -Po '((^,)+)' | head -4 | tail -1)
}
function print_normal_header()
{
    printf "%-${longestshort}s   %-${longestlong}sn" "Command" "Game Title"

    for (( i=0; i<$(($longestshort + $longestlong + 2)); i++ ))
    do
        echo -n "-"
    done
}
function print_verbose_header()
{
    printf "%-${longestshort}s   %-${longestlong}s   %-${longestpathf}s   %sn" "Command" "Game Title" "Path" "Task Name"
        
    for (( i=0; i<$(($longestshort + $longestlong + $longestpathf + $longestservicename + 4)); i++ ))
    do
        echo -n "-"
    done
}
function print_normal_record()
{
    printf "%-${longestshort}s | %-${longestlong}sn" "$1" "$2"
}
function print_verbose_record()
{
    printf "%-${longestshort}s | %-${longestlong}s | %-${longestpathf}s | %sn" "$1" "$2" "$3" "$4"
}
function print_help()
{
    echo -e "Launch program on remote Windows PC and change monitor inputs automatically.n"
    echo -e "USAGE"
    echo -e "-----"
    echo -e
    echo -e "e(3mplay (COMMAND)e(0m"
    echo -e "Launch the game defined by the COMMAND parameter.n"
    echo -e "e(3mplay -le(0m"
    echo -e "Print a formatted table of games saved to the games.list file excluding file paths.n"
    echo -e "e(3mplay -lve(0m"
    echo -e "Print a formatted table of games saved to the games.list file including file paths and task names.n"
    echo -e "e(3mplay -f (PATTERN)e(0m"
    echo -e "Search for a matching PATTERN in the games.list file and list results excluding file paths.n"
    echo -e "e(3mplay -fv (PATTERN)e(0m"
    echo -e "Search for a matching PATTERN in the games.list file and list results including file paths and task names.n"
    echo -e "e(3mplay -a (COMMAND) (TITLE) (PATH) (TASK)e(0m"
    echo -e "Add a game to the list that is located at the PATH on the Windows machine, is started by using the COMMAND parameter, and can be easily referenced in the -l functionality by the game's formal TITLE, which shows up in task manager as TASK (typically a ".exe" file).n"
    echo -e "tFilepath shortcuts for PATH"
    echo -e "t---------------------------"
    printf  "t%-10s %-1s %-50sn" "%STEAM%" "=" "$STEAM"
    printf  "t%-10s %-1s %-50sn" "%DESKTOP%" "=" "$DESKTOP"
    printf  "t%-10s %-1s %-50snn" "%APPDATA%" "=" "$APPDATA"
    echo -e "e(3mplay -r (PATTERN)e(0m"
    echo -e "Search for a matching PATTERN in the games.list file and remove it from the games.list file. This will generate a games.list.bak file, which is the games.list file before the specified program is removed.n"
    echo -e "e(3mplay -?e(0m OR e(3mplay --helpe(0m"
    echo -e "Print this help text.n"
}
function list_games()
{
        for (( IFS=" " i=0; i<$ctr; i++ ))
    do
        print_normal_record "${short(i)}" "${long(i)}"
        done
    echo
}
function list_games_verbose()
{
        for (( IFS=" " i=0; i<$ctr; i++ ))
    do
        #Remove/replace backslash, quote marks, and path shortcuts from path and print result in table
        pathf="${path(i)//\/}"
        format_pathf
            print_verbose_record "${short(i)}" "${long(i)}" "$pathf" "${servicename(i)}"
        done
    echo
}
function run_game()
{
    isRunning=0

    echo "Changing monitor input and launching winrun with parameters "start $1""
    sudo chmon $display
    winrun "start $1"

    while (( 1 ))
    do
        #Wait for program to actually show up in Task Manager (accounts for user messing around in launcher
        if ( -n $(winrun "tasklist /fi "SESSIONNAME eq CONSOLE" /fo list" | grep -i $task) ) && (!isRunning); then
            isRunning=1

        #Switch monitor inputs when program is no longer running
        elif ( -z $(winrun "tasklist /fi "SESSIONNAME eq CONSOLE" /fo list" | grep -i $task) ) && (isRunning); then
            echo "No longer seeing $task running on Window system, changing display input."
            winrun "run $ControlMyMonitor /SetValue \\.DISPLAY1Monitor0 60 4"
            break;
        fi
    done
}

#Load games from games.list file
if ( -f $games )
then

    #Read games list
    while IFS= read -r line
    do
        short($ctr)=$(echo $line | awk -F, '{print $1}')
        long($ctr)=$(echo $line | awk -F, '{print $2}')
        path($ctr)=$(echo $line | awk -F, '{print $3}')
        servicename($ctr)=$(echo $line | awk -F, '{print $4}')
        ((ctr++))
    done < $games
else
    #Make games list file if it does not exist
    echo $games file  not found, creating!
    touch $games
fi

#Check for script arguments
while ( "$#" != "" )
do
    case "$1" in
        -l)#List games

            if ( "$2" )
            then
                echo -e "Detected arguments after ""$1"". Ignoring, as these are not used...n"
            fi

            get_normal_header_spacing
            print_normal_header
            list_games | sort
            break;;

        -lv)#Display games list with more info
            
            if ( "$2" )
            then
                echo -e "Detected arguments after ""$1"". Ignoring, as these are not used...n"
            fi

            get_verbose_header_spacing
                        print_verbose_header
            list_games_verbose | sort
                        break;;

        -f)#Find for parameter and display

            if ( ! "$2" )
            then
                echo "Missing search parameter!" >&2
                break
            fi
            if ( "$3" )
            then
                echo -e "Detected arguments after ""$2"". Ignoring, as these are not used...n"
            fi

            get_normal_header_spacing
            print_normal_header
            echo
            list_games | grep -i "$2" | sort
            break;;

        -fv)#Find for parameter and display with more info

            if ( ! "$2" )
            then
                echo "Missing search parameter!" >&2
                break
            fi
            if ( "$3" )
            then
                echo -e "Detected arguments after ""$2"". Ignoring, as these are not used...n"
            fi

            get_verbose_header_spacing
            print_verbose_header
            echo
            list_games_verbose | grep -i "$2" | sort
            break;;

        -a)#Add game to list

            if ( ! "$2" )
            then
                echo "Missing program command string!" >&2
                break

                elif ( ! "$3" )
                then
                    echo "Missing program title!" >&2
                    break

                    elif ( ! "$4" )
                    then
                        echo "Missing program path!" >&2
                        break

                        elif ( ! "$5" )
                        then
                            echo "Missing program task name!" >&2
                            break
            fi
            if ( "$6" )
            then
                echo -e "Detected arguments after ""$5"". Ignoring, as these are not used...n"
            fi

            #Check for duplicate entry
            check_for_duplicate "$2"
            check_for_duplicate "$3"
            check_for_duplicate "$4"

            #If no duplicate is found, add entry
            if ( ! $match )
            then
                pathf="${4//\//}"
                echo ""$2","$3","$pathf","$5"" >> "$games"
                echo "Added the following record:"
                echo
                print_verbose_header
                echo
                format_pathf
                    print_verbose_record "$2" "$3" "$pathf" "$5"
            fi

            break;;

        -r)#Attempt to remove game from list

            if ( ! "$2" )
            then
                echo "Missing search parameter!" >&2
                break
            fi
            if ( "$3" )
            then
                echo -e "Detected arguments after ""$2"". Ignoring, as these are not used...n"
            fi

            rctr=0
            while IFS= read -r line
            do
                if (( -n $(echo $line | grep "$2") ))
                then
                    match=1

                    get_record $rctr "$line"
                    echo "Discovered the following matching record:"
                    echo
                    print_verbose_header
                    echo
                    pathf="${path($rctr)}"
                    format_pathf
                        print_verbose_record "${short($rctr)}" "${long($rctr)}" "$pathf" "${servicename($rctr)}"
                    echo                    

                    while (( $answer != "y" && $answer != "n" ))
                    do
                        echo -n "Remove this record? (y/n) "
                        read -r answer </dev/tty
                    done

                    if ( $answer == "n" )
                    then
                        echo "$games not changed."
                        break
                    fi

                    echo
                    echo "Removed the following record:"
                    print_verbose_header
                    echo
                    print_verbose_record "${short($rctr)}" "${long($rctr)}" "$pathf" "${servicename($rctr)}"

                    #Shift all entries beyond the removed entry down one
                    for (( i=$rctr; i<ctr; i++ ))
                    do
                        short(i)=${short(i+1)}                      
                        long(i)=${long(i+1)}
                        path(i)=${path(i+1)}
                        servicename(i)=${servicename(i+1)}
                    done

                    #Rebuild games.list
                    cp $games $games.bak
                    rm $games
                    for (( i=0; i<(ctr-1); i++ ))
                    do
                        echo "${short(i)}","${long(i)}","${path(i)}","${servicename(i)}" >> $games
                    done

                    break
                fi

                ((rctr++))
            done < $games


            if ( ! $match )
            then
                echo -e "Did not find match for ""$2"" in "$games""
            fi
            break;;

        -? | --help)#Print help text

            if ( "$2" )
            then
                echo -e "Detected arguments after ""$1"". Ignoring, as these are not used...n"
            fi

            print_help
            break;;

        *)#Search for matching game

            if ( ! "$1" )
            then
                print_help
                break;
            fi

            if ( "$2" )
            then
                echo -e "Detected arguments after ""$1"". Ignoring, as these are not used...n"
            fi

            echo -n "Checking if ""$1"" matches a known game in games.list... "
            shopt -s nocasematch
            for (( i=0; i<$ctr; i++ ))
            do
                if (( "$1" == "${short(i)}" )); then
                    path(i)="${path(i)//%STEAM%/$STEAM}"
                    path(i)="${path(i)//%DESKTOP%/$DESKTOP}"
                    path(i)="${path(i)//%APPDATA%/$APPDATA}"
                    prgm="${path(i)}"
                    task="${servicename(i)}"
                    break
                fi
            done
            shopt -u nocasematch

            #If there was a match, run program. Otherwise, run first arg as is.
            if ( "$prgm" != "" )
            then
                echo "Found!"
                run_game "$prgm"
            else
                echo "Not found!"
                run_game "$1"
            fi

            break;;
    esac
    shift

#LANG=$oLang LC_ALL=$oLcAll

done

c – Why doesn’t my printf print?

Why don’t my printf’s print? I am trying to make and use functions for the first time and I am at a loss as to why the program seems to be active doing something, but doesn’t get passed the first function. Why doesn’t the code get far enough to print?


#include <stdio.h>
#include <math.h>

int i, j, N=50000;
double k = 8.9875517923e9;
double e = 1.6021892e-21;
double a, m = 9.1093837015e-31, meN = 23.259582e-27;  //N=2.3258671e-26 kg
double f, voltage, current;
double q1, q2, r, t=1, dt=1, vx, vy, X, Y, V, Vx1, Vy1;


double compute_force_on_i(double voltage, double current)
{
    f = sqrt((2*m)/e) * current * sqrt(voltage);  //m*a + k*sqrt(q1*q2/(r*r)   //newtons = sqrt((2*m)/e) * current * sqrt(voltage)
    return f;
}
double compute_velocity_on_i(double voltage, double meN)  // x = v*t  vx = sqrt(2eV/m) vy = sqrt(2eV/m)
{
    vx = sqrt(2*e*voltage/meN), vy = sqrt(2*e*voltage/meN);
    return vx && vy;
}
double update_position_on_i(double vx, double vy)
{
    X = (f/m)*dt, Y = (f/m)*dt;  //X = vx*t, Y = vy*t;    //  dsx = (f/m)*dt, dsy = (f/m)*dt
    return X && Y;
}

int main(int argc, char *argv()){

    printf("Enter the voltage in volts. ");
    scanf("%le", &voltage);

    printf("Enter the current in amps. ");
    scanf("%le", &current);

    printf("Enter the distance in meters. "); //grid to grid distance
    scanf("%le", &r);

    printf("Enter the number of particles. ");
    scanf("%de", &N);


for (i = 0; i < N; i++) do{
printf("printf1");
  for (j = 0; j < N; j++ ) do{
    if (i == j)
      continue;
    //end if
    }while(i != j);
printf("pritnf2");
    compute_force_on_i(voltage, current);
printf("pritnf3");  //end for
    }while(i != j);

 a=f/m;

  compute_velocity_on_i(Vx1, Vy1);

printf("nf_%le, vx_%le, vy_%len", f, vx, vy);

  update_position_on_i(X, Y);
//end for

printf("nf_%le, vx_%le, vy_%len", f, X, Y);
return 0;
}

What is the difference between printf and scanf?

Hello friends,

What is the difference between printf and scanf?

Why have this segmentation error, but if I delete the * in printf (), I do not have it?

`#include

understand

int alloc (int * pointer, int num) {
scanf ("% d", & num);
pointer = (int ) malloc (numsizeof (int));
return (* pointer);
}

int main () {
int * pointer;
int num;
alloc (pointer, num);
printf ("% d", * pointer);
returns 0;
} `

bash – printf output format

I have the following variable that generates a certain format:

MSG_AUX=$(cat ${FILE_AUX})
MSG=`printf '%sn' '---' "${DATE} - ${HOSTNAME}" '---' "$MSG_AUX"`

The result is:

---
01/05/2019
---
dato 1

dato 2

dato 3

The folder FILE_AUX that I assign to the variable MSG_AUX It contains the following elements (without line breaks):

dato 1    
dato 2    
dato 3

I would need not to blow up lines with the printf; that is, I will take a break offline:

---
01/05/2019
---
dato 1    
dato 2    
dato 3

How should I adapt it?

Improved `printf` with C ++ variadic models

I'm currently working on learning C ++ variadic models and I wanted to create an example of using them that is less trivial than my book. I decided to create a printf interface modification where the type of each argument did not need to be specified. Here is an example:

print(std::cout, "Welcome to this computer program, % son of %!", "bob", "some klingon");
//prints "Welcome to this computer program, bob son of some klingon."

I've also added the possibility of escaping a % character (or any other character, such as the escape character itself) with a .

#include 
#include 
#include 

namespace printpriv{
    using itr = std::string::const_iterator;

    template
    void print(std::ostream &out, itr it, itr end, const T &t){
        bool flagged = false;
        while(it != end){
            if(flagged){
                out << *it;
                flagged = false;
            }else{
                if(*it == '/'){
                    flagged = true;
                }else if(*it=='%') {
                    out << t;
                }else{
                    out << *it;
                }
            }
            ++it;
        }
    }

    template
    void print(std::ostream &out, itr it, itr end, const T &t, const Args &...args){
        bool flagged = false;
        while(it != end){
            if(flagged){
                out << *it;
                flagged = false;
            }else{
                if(*it == '/'){
                    flagged = true;
                }else if(*it=='%') {
                    out<
void print(std::ostream &out, const std::string &pattern, const Args &...args){
    printpriv::print(out, pattern.begin(), pattern.end(), args...);
}

int main() {
    print(std::cout, "Hello, I am a % and my name is %.n", "dog", "capybara");
    print(std::cout, "There are % % here.n", 32, std::string("capybaras"));
    print(std::cout, "There are no arguments here.n");
    print(std::cout, "I am 80/% sure that this will work.", 10); //at least one argument is needed to prevent calling the version that just passes through the pattern to the output stream
    return 0;
}

In this code, I have these main concerns, but I am also interested in a standard code revision:

  • There is a huge amount of code duplication between the two privprint::print overloads to handle the analysis of the input model, but I do not see the best way to avoid it.
  • the privprint namespace stores two functions that the main print method uses internally, in addition to one using declaration. This is not ideal because I consider the contents of this namespace as a detail of the implementation of the. print function, so it should not be accessible to the user. Adding "priv" in the name is a decent way to warn other programmers who can work with this code, but one thing the compiler applies would be ideal. My instinct is to put the declaration using and the function models that are in privprint in printname, but C ++ does not allow function templates to appear in this one (it also does not seem to allow any templates, which breaks with all the usual ways around this restriction of function, such as a type of functor or lambda).
  • The implementation here considers an incorrect number of non-escaped %s and the arguments to substitute constitute undefined behavior, but it would be better if it was a compilation error when the string is available. I could make it a runtime error, but it would add runtime cost and thus violate the C ++ philosophy of preferring undefined behavior to higher run cost. Despite this, I do not see any effective way to allow models to parse the string at run time. I think this is possible however using some constexpr. That's why a template-meta-programming tag is on this issue.

How to handle printf in C language

Hello

How can I put something after the variable in a printf.
Ex:

printf ("Enter a value for the position: [%d", l); printf(" ,%d", c); printf(" ]");

I'm using the example above, but I was wondering if it was possible to do something similar to the pseudocode:
Ex:

printf ("Enter a value for the position: [%d", l, ",", c, " ]");

The end result would be something like:

Enter a value for the position [ x, y]: