FAQ Database Discussion Community


printing a double variable with %f and the terminal is displaying a “?” [duplicate]

c,printf,double
This question already has an answer here: Arduino: printf/fprintf prints question mark instead of float 3 answers I am completely lost on what to do with this issue. I'm not very familar with c language, but I know enough to program my Atmel MCU for a controls project. I'm...

fprintf valgrind error

c,printf,valgrind
My program sorts the input from a text file and then fprintf it into output file. However valgrind reports some nasty errors for fprintf calls, which I do not understand. Any hints whats the reason for them? #include <stdio.h> #include <stdlib.h> #include <string.h> void * mymalloc (int size) { static...

Why the division of two integers return 0.00? [duplicate]

c,floating-point,int,printf,format-specifiers
This question already has an answer here: printf(“%f”, aa) when aa is of type int [duplicate] 2 answers Every time I run this program I get different and weird results. Why is that? #include <stdio.h> int main(void) { int a = 5, b = 2; printf("%.2f", a/b); return 0;...

Why do the strings output using fprintf end up not being written to the output file if my program is terminated via CTRL-C?

c,file-io,printf
Why does fprintf give different results in the following example programs? Example 1: int main(){ FILE *f; char buf[512]; char name[128] = {"filename"}; f = fopen(name, "w"); fprintf(f, "asdas\n"); fprintf(f, "asdas\n"); while(1){} return 0; } If I terminate this program using CTRL+C, I get an empty file named filename. However,...

std::cout and printf array

c++,c,printf,cout,format-specifiers
int arrSize = 10; double* arr = new double [arrSize]; for(int i = 0; i < arrSize; i++){ arr[i] = i; } for(int i = 0; i < arrSize; i++){ printf("%d", arr[i]); //std::cout<<arr[i]; } Here printf() prints 0000000000. cout prints 0123456789. Why ?...

Why does command prompt show numbers before I begin?

c,file-io,printf,scanf
The command prompt shows numbers before program begins. Why? 2687688 is given but the numbers won't write to file? #include <stdio.h> #include <conio.h> int main(void){ FILE*nfPtr; int n; if ((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","w"))==NULL) { printf ("Sorry! The file cannot be opened\n"); } else {//else 1 begin printf("Enter numbers to be stored in file\n");...

Use a variable into a sql statement - c interface

sql,c,sqlite,printf
I am new to SQLite but I need it in my c program to analyse tables. If I use as sql statement: char *sql; sql = "SELECT * FROM table;"; it perfectly works. But I would like to have sql = "SELECT X FROM table;"; where X is a variable...

How do you type something on the same line of text in C [closed]

c,printf,scanf
I was wondering how can you type something in one line in C? This is the normal way it outputs. Output > <text> Instead > <text> ...

How many parameter in this printf() function? [duplicate]

c,methods,arguments,printf
This question already has an answer here: How does printf handle its arguments? 5 answers I am very new to programming. Now I am learning C. Please look at this following code snippet - printf("StudentId: %d CGPA: %f", id, cgpa); printf("Name: %s StudentId: %d CGPA: %f", name, id, cgpa);...

Why is my C code printing out an extra line of rows?

c,loops,for-loop,macros,printf
#include <stdio.h> #define rows 500 //can define rows as any number int main() { int i,j; for(i=0;i<=rows;++i) { for(j=0;j<(2*i+1);++j) { printf("* "); } printf("\n"); } return 0; } So here is my code, what it does is it prints the number of rows set by #define and creates a right...

What does a # sign after a % sign in a scanf() function mean?

c,input,printf,scanf,format-specifiers
What does the following code mean,in C scanf("%d%#d%d",&a,&b,&c); if given values 1 2 3 it gives output as 1 0 0 P.S- I know it is used with printf() statement but here in scanf() statement it gives random behaviour....

Why does this print statement stop program from crashing in C?

c,struct,crash,printf,dfs
I have the following program which first stores the direct flights between some cities and then uses DFS to query if two cities are connected by indirect flights. The program kept crashing during the query step, so I tried to find the problem using print statements and strangely the program...

Switching to cout from printf - Complex format specifier patterns

c++,c,printf,cout
I have to rewrite a logging system in C++ as part of project requirements (everything has to be C++ instead of C now), and there are a number of ways in which we log things like mathematical data and pointer addresses. It is fairly common to see a log like:...

Why is this floating point addition result not correct?

c,floating-point,printf,addition
I am trying to calculate the time in buffer in microseconds. But I don't understand why the floating-point operation result of my code is not correct. float time, sec; int h, m; sscanf(16:41:48.757996, "%d:%d:%f", &h, &m, &sec); printf("buffer %s\n",buffer); printf("hour %d\n",h); printf("minute %d\n",m); printf("seconde %f\n",sec); time=3600*h+60*m;+sec; printf("%f\n",time); When I execute...

When displaying the value of variable “int a = 011”, I get 9. Why? [duplicate]

c,printf,decimal,octal,format-specifiers
This question already has an answer here: What does it mean when a numeric constant in C/C++ is prefixed with a 0? 7 answers printf with “%d” of numbers starting with 0 (ex “0102”) giving unexpected answer (ex '“66”) 3 answers With this code snippet: int a = 011;...

Trouble getting PrintWritter to correctly print to .txt after my nested loop

java,nested,printf,printwriter
I'm asked to use PrintWriter to print grids of multiplication problems to a .txt file. Everything is working well but I'm having some serious trouble with getting my code to print the way I'm asked. I've been using printf with left/right indentation. Any help would be very appreciated. I didn't...

printf() function behavior

c,printf,behavior,format-specifiers
int main(){ // Comment the next line, Garbage value is printed. However, this shows an integer value. int x=32; printf("%d"); return 0; } Any reason for this behaviour, or is it random??...

Print each word in a separate line from an input string

c,string,char,printf,scanf
I'm having trouble printing each word in a separate line from an input string in C. The question from the assignment I'm doing states: Take a sentence as input and print its words in separate lines. My Code: #include<stdio.h> int main() { int i; char s[100]; scanf("%s", s); for(i=0; s[i]!='\0';...

Implement fmt::Display for Vec

printf,rust,traits
I want to implement the fmt::Display for a nested struct commonly used in my code. // The root structure pub struct WhisperFile<'a> { pub path: &'a str, pub handle: RefCell<File>, pub header: Header } pub struct Header{ pub metadata: metadata::Metadata, pub archive_infos: Vec<archive_info::ArchiveInfo> } pub struct Metadata { // SNIP...

How do I identify the last variable argument? [duplicate]

c++,char,arguments,printf,va-arg
This question already has an answer here: Count number of parameters in C variable argument method call 3 answers So in my function I want to take a variable number of char pointers. void myFunction(char *_Name, ...); Only, when I iterate through the arguments my code breaks because I'm...

Is there a way to print something in console that doesn't scroll down? (In C)

c,printf
Well, maybe if I offer a little context this will be more understandable. I want to print "Inventory" in the first line of my main, but I don't want "Inventory" to move from its place, so, while the rest of my commands show in console, and will scroll down, this...

c++ - how to convert char to int?

char,int,printf
I try to write a function who convert a string to an integer (like atoi). I don't see why my function "convertir" don't print my variable "res " whereas "test 1 " "test 2"... "test 4" is printed. I let you look at my code and if you see something...

assign struct's address to pointer

c,pointers,struct,printf,addressof
Consider this code: #include<stdio.h> #include<assert.h> #include<stdlib.h> #include<string.h> struct Person { char *name; int age; int height; int weight; }; struct Person Person_create(char *name,int age,int height,int weight) { struct Person who; who.name=strdup(name); who.age=age; who.height=height; who.weight=weight; return who; } void Person_destroy(struct Person who) { free(who.name); } void Person_print(struct Person who) { printf("%s...

can't store and print float array values inside a struct [closed]

c,arrays,struct,printf
I'm trying to write to a vector in a struct, but it is not working. Here's my code: #define BUFFER_SIZE 100 typedef struct { float vec[BUFFER_SIZE]; int j; } send; int main(){ send strucSend; for(i=0; i<BUFFER_SIZE; i++){ strucSend.vec[i]=i+1; strucSend.vec[i]=100; printf("created vec: %d \n", strucSend.vec[i]); } } When I print it,...

Nasm, not printing the correct value

c,assembly,floating-point,printf,nasm
I've made a nasm procedure that calculates the eucledian distance between two vectors of a certain size. This nasm function is called from a C file which get the result of the function. I've tested, and it works, the value returned is correct, I can print it withoud any problem....

Issue with bit-fields

c,struct,printf,bit-fields
I have a question related to bit-fields in C. Here I have such a structure: struct Register { int bit:1; }; int main(void) { struct Register bit = {1}; printf("\nbit = %d", bit.bit); return 0; } Can you please explain me why do I get: bit = -1 ...

Overlapping and too long integer values in dynamic c structs

c,printf,buffer
I have the following problem. I need to create a list of savestates with dynamical length. That's why I decided to create a list by defining some structs and connecting dynamically created structs together to build a list of structs which can dynamically be extended and so on. However, some...

How to check if argv[count] is an integer

c,pointers,printf
I'm trying to create a command line application in C++ and I want to make sure that the input is an integer after a certain command argument. For this example, I want to check if the next argument is an integer after the "-p" command argument. Here's the snippet of...

Do-While loop in C - error at printing

c,printf,do-while
I am making a little program that takes as input the answer to the question "Are you an adult?" as a character like that: bool adult() { char answer; do { printf("Are you an adult? [y/n]\n"); answer = getchar(); } while (!(answer == 'y' || answer == 'n')); return (answer...

What does 'printf -v' do?

bash,printf
After having come across several times this printf -v in bash script examples on the net, as well as several questions on stackoverflow, I could not find a proper explanation in the printf manpages. man printf or man 3 printf do not help me. Where do I have to look...

Most carefull way to concatenate strings in C

c,string,csv,printf,sd-card
My firmware in one cycle per 10 second is moving string to the output (csv file on SD card). The problem is that string sometimes in non-deterministic way is changing adding values that shouldn't be there or put space in the middle. Is this related to sprintf function or dynamic...

How to make proper alignment with printf

ruby,printing,printf
I am trying to make output that should look like this: I am using this statement: FILE_TYPES.each_key {|key| printf "%20s %s\n", "--[no]" + key.to_s, FILE_TYPES[key.to_sym]} Its result looks like this: ...

Need to understand printf functioning deeply

c,printf
I tried the below mentioned code and to my surprise getting somewhat relevant output. void main( ) { char s[]="USMComputer"; printf("%*.*s",-5, 4, s+3); } This outputs Comp. Can someone explain this? ...

C: Why does snprintf only writes 4 characters to my variable?

c,printf,malloc
So I'm trying to return a variable that contains a string with some parameters determined inside the function. char* render(my parameters) I'm declaring my variable like this: char *string = malloc(sizeof(char) * 50); This is an excerpt of my function: switch(INST_OPCODE){ case 0x00: inst->name = malloc(sizeof(char) * (strlen("add") + 1));...

Why is _stprintf_s overwriting other variables but _stprintf is not?

c++,winapi,printf,malloc
I'm using visual studio for win32 programming class. I have a global array of string declared as TCHAR **bufTh allocated in memory like bufTh = (TCHAR**)malloc(nOfTh*sizeof(TCHAR*)); for (i = 0; i < nOfTh; i++) bufTh[i] = (TCHAR*)malloc(BUF_LEN*sizeof(TCHAR)); then I have some threads, each of them writing on a different string...

if statement for string comparison is not executing properly

c,string,input,printf,scanf
I am trying to write a simple program for finding out areas of different shapes.The program is compiled fine but when it runs it does not give me the right answer. I mean When it runs it asks: What do you want to find area of? and when I type...

Adding two integer variables and displaying output C

c,printf,undefined-behavior,format-specifiers
I am trying to create a simple program in C, that adds two numeric variables. I have tried to validate the inputs, however now the program does not display an answer, simply 0.000000000 #include<stdio.h> int input, temp, status, numberOne, numberTwo, ans; int main(void){ first(); second(); add(); } int first(void){ printf("Please...

Repeating the format specifiers in awk

awk,printf,gawk
I am trying to format the output of the AWK's printf() function. More precisely, I am trying to print a matrix with very long rows and I would like to wrap them and continue on the next line. What I am trying to do is best illustrated using Fortran. Consider...

How to read and write files using printf and scanf in C? [closed]

c,file,printf,scanf
A little backstory: Some years ago, I was on a algorithm contest. By that time, I was learning C, and I didn't know how to write or read files using the normal methods. In order to no get confused by new methods and syntax, a C wizard, told me to...

What is the printf format for fixed string?

c,printf
Is this safe or UB ? char x[5] = { 'a', 'b', 'c', 'd', 'e' }; printf("%5.5s\n", x); What is the correct printf format to print a non-zero-terminated string ? (Or what is the format to print the first N characters of a c-string ?)...

Precedence of Evaluation and Assignment operators in printf parameters

c,printf
#include<stdio.h> int main() { int k=35; int a=k==35; printf("%d %dn", k==35, k=50); printf("%d %dn", a,k=50); return 0; } In the first printf statement, why k==35 evaluates to 0 ? I assume this may be because of the fact that k=50 assignment happens before k==35 evaluation. However, I do not understand...

Double check the size of a buffer

c,printf,overflow
I have a doubt about a potential buffer overflow in a library I developed, where there is the following API that can be called from external application. I've tried to find a possible solution but I didn't find yet the "right" one. The API is the following: char* strftime_ISO8601(uint64_t ns,...

Unwanted line break in C

c,linux,printf,newline,fgets
I have created a little script in C which displays text in a Linux console, but I found one problem - the script adds a line break at the end of text. I have no idea why, normally I should get line break after /n. #include <stdio.h> #include <stdlib.h> int...

Getting different output for cout and printf while printing same variable

c++,printf,cout,sin
Using Devc++ for printf getting 0.00000 and for cout getting some weird output. #include<iostream> #include<cmath> #include<stdio.h> using namespace std; main() { float i,j=M_PI; i=sin(j); printf("%f \n",i); cout<<i; } ...

Is it possible to use BASH/bc/printf to round a float to it's first significant figure?

bash,math,printf,rounding,bc
I've found tons and tons of information about rounding a float to a specific number of decimal places by using 'scale' with BC and '%.xf' with printf, but if I'm working with numbers that don't always have the same format like I've shown below, is there a way to round...

Output EOF using %f

c,io,printf,eof,format-specifiers
#include<stdio.h> int main() { printf("%d",EOF); } generates -1 which is totally fine, but #include<stdio.h> int main() { printf("%f",EOF); } produces 0.000 . How can someone explain this when the expected output is -1.000?...

Programatically Ignore printf

c++,printf
I'm using someones library that printf's out an error message when a connection to a device is unsuccessful. The library code prints out nothing when a connection is successful. I periodically check (loop & sleep) to see if a device is connected but I only want to print out when...

How to print a string using printf without it printing the trailing newline

c,string,printf,null-terminated
I'm trying to print some strings using printf() but they are null terminated having trailing newline and that messes with the formating: printf("The string \"%s\" was written onto the file \"%s\"", str, fname); Say the string contains "The Racing car." and the file name is "RandomText1.txt" This prints: The string...

C format string when writing to file

c,printf,sprint
I'm having a bit of noob confusion how to use a formated string when writing to a file, and more in general I guess about sprintf. #include <stdio.h> int main(int argc, char* argv[]) { FILE *fp; const char *exts = ".txt"; char *saveToPath; sprintf(saveToPath, "/Path/To/My/File%s", exts); fp = fopen(saveToPath, "w+");...

printf bash strange behavior

bash,shell,printf
I have written 2 logging methods in bash script as: # Function to log information function print_info() { format="$1" shift printf "$(date +'%F %T') ${SCRIPTNAME}: INFO: $format\n" "[email protected]" | tee -a ${LOGFILE}; } # Function to log error function print_error() { format="$1" shift printf "$(date +'%F %T') ${SCRIPTNAME}: ERROR: $format\n"...

What is this C programming reading?

c,file-io,printf
This is the code I am trying to understand: #include <unistd.h> #include <fcntl.h> #include <stdio.h> int main(void){ unsigned long word; ssize_t nr; int file = open("koray.txt",O_RDONLY); nr = read(file,&word,sizeof(unsigned long)); printf("%li\n",word); } koray.txt has only 1 character that is k. When I run the program I see: [email protected]:~$ ./a.out 4195435...

Program crash while trying to print a bidimensional array

c,multidimensional-array,printf
as the title says, my program crashes when i try to print a bidimensional array. The error is surely printf in function printarray, but i couldn't understand why it lead to crash. #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #define COL 40 #define ROW 40 void printarray(int array[COL][ROW], int col, int...

How to print the string representation of an “enum” in Go?

go,enums,printf
I've looked at the various official sources for how to do this but I can't find it. Imagine you have the following enum (I know golang doesn't have enums in the classic sense): package main import "fmt" type LogLevel int const ( Off LogLevel = iota Debug ) var level...

How to print a string multiple times referencing it only once?

c,string,printf
This code: #include <stdio.h> void main() { char *csv_delimiter = ","; printf("col1%scol2%scol3%scol4\n", csv_delimiter, csv_delimiter, csv_delimiter); } has this output: col1,col2,col3,col4 That's exactly what I need. But I have to refer to the pointer csv_delimiter multiple times. What if I had 1 thousand columns? Is there a way to refer to...

how to use elipsis (…) [duplicate]

c,printf
This question already has an answer here: How to pass variable number of arguments to printf/sprintf 7 answers i want to write a function in c which uses the elipsis (...) argument, but i have no idea how it works. i want to do something like this: void error(const...

Mathematical expression in print command in Linux

linux,shell,printf
I can't get my mistake in this command: a=2 b=5 c=3 printf "%.2f\t" "'$a'+'$c'*'$b'" > ofile.txt I am getting the value as 50.00. But I should get it 17.00. How to do this when a, b, c are floating values? e.g. a=2.4, b=5.1 and c=3.2...

MISRA C 2004 10.1, signedness of printf “%x”

c,printf,type-conversion,format-specifiers,misra
I'm getting errors from our static analysis tool about the following snippet: uint8_t value = 24U; char buffer[512]; int chars_printed = snprintf(buffer, sizeof(buffer), "The value in hex is 0x%02hhX\r\n", value); The error is: MISRA-2004 Rule 10.1 violation: implicitly converting a non-constant expression in a function argument. Converting "value", with underlying...

Why does printf require a mandatory parameter?

c,printf
The definition of printf function in C Language is: int printf(const char * _Format, ...); The same is for scanf and a lot of similar functions where is managed a variable number of arguments. Why is there a _Format mandatory parameter?...

How to fprintf some data to a file,and divide them into different columns when opened by excel

c,printf
I want to fprintf three number to a text file and, I try to make it divided into different columns when i open the file with a excel.( now, it's in one column) Below part of my code FILE *fp; FILE *![enter image description here][1]fp1; FILE *fp2; fp = fopen("exdata1.csv",...

Printing Int variable in Float format [duplicate]

c,gcc,int,printf,format-specifiers
This question already has an answer here: What is printf's behaviour when printing an int as float? 3 answers I'm using gcc to compile this: int a=1; printf("%d\n",a); printf("%f\n",a); printf("%f\n",(float)a); I get: 1 0.000000 1.000000 Why does the implicit conversion give a wrong output?...

Unexpected output printf statement [duplicate]

c,macros,printf,ternary-operator
This question already has an answer here: Why is “i” variable getting incremented twice in my program? 8 answers Why outputs of i and j in the following two printf()s are different? #include <cstdio> #define MAX(x,y) (x)>(y)?(x):(y) int main() { int i=10,j=5,k=0; k==MAX(i++,++j); printf("%d %d %d\n",i,j,k); i=10,j=5,k=0; k=MAX(i++,++j); printf("%d...

fprintf outputting ')' in txt file

c,printf
I have been trying to create a c program to print the current content of a .txt file, allow the user the enter what content they wish to be there instead, and then print that content over the previous txt file. However the resulting .txt file has ')' printed, replacing...

A beginner questions about printf, java

java,string,printf
I'm learning Java by myself and through tutorials online. Just wondering in a printf statement, what does the different %s, %d, %15, %7, %12.2(and so on...) mean? Couldn't find any explanation anywhere online, so I'm turning to you. ...

How to fscanf from a .csv which is a output of fprintf

c,printf,fscanf
I want to fscanf a csv file which is a output of fprintf, I set the same format but it didn't work, which means when I use that function to fscanf the file I just made, it didn't succuss, even didn't get into the while-loop. So, how to modify it...

why it is allowed to pass insufficient number of parameters when calling a function in C?

c,printf,parameter-passing,function-call
I know that function prototyping is mandatory in C++ if the function is defined after the main() function, but it is optional (but recommended) in C. I recently wrote a simple program that performs addition of 2 numbers, but by mistake used the dot operator instead of a comma when...

Segmentation fault when printing the linked list

c,linked-list,segmentation-fault,printf
I've been reading the Stanford tutorial for linked lists. I used one of the functions which creates a list of three numbers (1,2,3). The function itself doesn't print the result, so I decided to test it myself. However, when I run it, it gives me segmentation fault. With that being...

Linux bash printf format with color assign to variable

linux,bash,printf
I just want a String (including coloring) be formatted by printf command and assign the result to a variable. Without assigning it to a variable it works fine, but as soon as I assign the result to a variable and write the result, the format is gone. My example: RED=$'\033[0;31m'...

print filenames into scripts in bash

bash,printf,echo
How do you print each name of a file from a directory into a string and make make new scripts? to print each file name for i in `ls new_manifest*`; do echo $i; done but when I try and print the rest of the string with $i like this is...

C Wrong Answer when squaring

c,printf,scanf
I'm learning C using C by Example. There is a question where we need to take an input integer and square it and print it to the screen. I'm having a strange error, when no matter what Int I enter it give me this output: Please enter a number. 5...

Mysterious printf argument when disassembling c program

c,assembly,stack,printf
So I have this c code: #include <stdio.h> int main(void) { int a; int b; int c; a=b=c=5; printf("Hi%d%d%dHi",a,b,c); } I compiled it on ubuntu with: gcc program.c -o program -ggdb -m32 -O2 And then disassembled it with: objdump -M intel program -d And in main printf() gets called like...

Confusion regarding a printf statement

c,printf
So I was running this code #include<stdio.h> int add(int x, int y) { return printf("%*c%*c",x ,' ',y,' '); } int main() { printf("Sum = %d", add(3,4)); return 0; } And can't seem to understand how does the following statement works return printf("%*c%*c",x ,' ',y,' '); So I tried writing a...

ANSI C What am I doing wrong with fwrite and the fread?

c,printf,fwrite,fread
I have the following code in which I attempt to write some data to a file on first execution, and then on second execution reads the file and prints the data to the screen. In the first execution it writes the data to the screen exactly as it is in...

Use of .* in printf

bash,unix,printf
I am trying to change the code of someone else. Can anyone explain this line of code to me? xs=`printf "%.*d" 3 $x` The $x is the loop variable, I do understand that....

What is the benefit of using System.out.print over System.out.printf?

java,printf,system.out,printstream
I have a question similar to Is there a good reason to use "printf" instead of "print" in java?. That question asks and is answered about the benefits of using System.out.print over System.out.printf. I am curious about the benefits to using System.out.print over System.out.printf in the first place. In my...

Why does printf convert large numbers?

c,printf,atoi
Why doesn't this work? printf("%d \n\n\n\n", atoi("11110010100")); it outputs -1774891788... I just want it outputted as it is. It seems to work just fine if the number is a bit smaller....

Alernative to printf(“%*s”,indent,message) in java?

java,printf,println
In C we can specify the amount to space to leave in printf , any similar way to do this in java? For example int space=6; char message[10]="hi"; printf("%*s",space,message); will print hi ...

For what reason printf does not correctly display the float?

c,casting,floating-point,printf
I hoped that in all cases showed 2.33, however, for what reason only in the second case this happened? printf("Without cast: %0.2f\n", 7 / 3); // Whitout cast: 0.00 printf("With cast: %0.2f\n", (float) 7 / 3); // With cast: 2.33 float x = 7 / 3; printf("With var: %0.2f\n", x);...

pow(1,0) returns 0? [closed]

c,printf,pow,ansi-c
Why does this: printf("%d\n", pow(1,0)); /* outputs 0 */ returns 0? I expected it to return 1....

Best way to print information when debugging a race condition

c,debugging,gdb,printf,race-condition
I am debugging an application to fix a segmentation fault that I suspect to be caused by a race condition. I'd like to put some print statements in the code, but I know for experience that adding calls to printf is not recommended since this could change the behavior of...

C++ equivalent of fprintf with error

c++,c,printf,stderr
If I have an error message called by: if (result == 0) { fprintf(stderr, "Error type %d:\n", error_type); exit(1); } Is there a C++ version for this? It seems to me that fprintf is C rather than C++. I have seen something to do with cerr and stderr, but no...

End while loop with ctrl+d, scanf?

c,while-loop,printf,scanf,eof
I want the user to be asked "how many circles" they wanna write until the user decides to end it with (Ctrl+d) which is EOF? extra question: if I write a letter for example "k" it will spam out circles. How do I change that? #include <stdio.h> int main ()...

Using Gawk and Printf in a Bash script

bash,scripting,printf,file-handling,gawk
I am trying to separate a file into smaller files with gawk and rename the smaller files in order from the original file. for i in *.txt do gawk -v RS="START_of_LINE_to_SEPARATE" 'NF{ print RS$0 > "new_file_"++n".txt"}' $i done The output gives me: new_file_1.txt new_file_2.txt ect... I would like the output...

printf printing extra “D” after getchar() call [duplicate]

c,printf,stdio
This question already has an answer here: Why does C program print 0D instead of 0? (When EOF sent as Ctrl+D) [duplicate] 2 answers I'm trying to work through "The C Programming Language", and I'm running into some issues with printf and the EOF character. I'm working the the...

Set precision dynamically using sprintf

c,printf,format-string
Using sprintf and the general syntax "%A.B" I can do this: double a = 0.0000005l; char myNumber[50]; sprintf(myNumber,"%.2lf",a); Can I set A and B dynamically in the format string?...

Don't stop printf at null termination (\0)

c,printf
printf stops printing at the first \0 it meets. Is there a way to force it to continue, for example if my string contains more characters after \0....

cudaPrintfInit and cudaPrintfDisplay failed

c,cuda,printf
I am working with GeForce 210, compute capability 1.2 and CUDA 6.5. I wish to print float values from my CUDA kernel, I have included "cuPrintf.cu" and "cuPrintf.cuh" in my project directory as well as included them in my code. It compiles fine and runs without errors, but prints nothing....

Calling free() causes my program to crash

c,crash,printf,malloc,free
I'm having a really weird issue where trying to call free on an allocated piece of memory causes my program to crash. Here's the relevant code: int i, count; char *specifier; char aisle[1]; count = 0; /*Find name of the new item and assign to the name field of new_node...*/...

Conversion from char to int and printing the decimal value

c,char,printf,decimal,ascii
char str[20]; printf("Enter anything\n"); scanf("%s",str); for(int i = 0 ; i<strlen(str) ; i++) { if( isdigit(str[i])) printf("%d",(int)str[i]); } I tried with the above code but the output is in ASCII values of the numbers rather then actual numbers. Like , input: "0" output: "48". When I try (int)(str[i]-'0'); instead of...

printf char as hex in c

c,printf
I expect ouput something like \9b\d9\c0... from code below, but I'm getting \ffffff9b\ffffffd9\ffffffc0\ffffff9d\53\ffffffa9\fffffff4\49\ffffffb0\ffff ffef\ffffffd9\ffffffaa\61\fffffff7\54\fffffffb. I added explicit casting to char, but it has no effect. What's going on here? typdef struct PT { // ... omitted char GUID[16]; } PT; PT *pt; // ... omitted int i; for(i=0;i<16;i++) { printf("\\%02x",...

Perl, print a letter after a constant format with sprintf()

perl,printf
So I'm trying to format a string with sprintf and I have a variable format setup for multiple use. But using it in my sprintf I cannot figure out how to print a letter after it without a Perl concatenation '.' which I feel is mixing two types of formatting...

ANSI escapes don't work in `printf`

bash,printf,sh,ansi-colors
When trying to use ANSI color escapes from a shell script, I was completely stuck, as the escape sequences (\e) were printed verbatim to the output. #!/bin/sh GREEN="\e[32m" RED="\e[31m" CLEAR="\e[0m" printf "${GREEN}test passed${CLEAR}\n" printf "${RED}test failed${CLEAR}\n" Produces \e[32mtest passed\e[0m \e[31mtest failed\e[0m ...

Trailing zero as a result of snprintf

c,arrays,string,char,printf
Today I ran into a problem that I just can't get the hang of. Consider this code snippet: static const char *LOG_MESSAGES[] = {"String1.", "A longer string 2.", "String 3"}; Somewhere in the main() function, I wrote: printf("%s\n", LOG_MESSAGES[1]);//Prints "A longer string 2." as expected. char rawLog[100] = {0}; printf("%s\n",...

How to save to file?

c,printf
I've got a problem with my project. I don't know how to add an option which will save to file the result's from console. I think i shoud use fprintf but nothing works. Please help ;D #include <stdio.h> #include <stdlib.h> #include <string.h> struct symbole { int symbol; int czestosc; };...

Convert char array into double [closed]

c,printf,double,fgets,atof
I have tried this: #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *txt1; char tam[13]; char tam1[13]; char tam2[13]; txt1 = fopen("C:/Users/Hugo/Documents/C/in2.txt","r"); if(txt1 == NULL) { printf("No se puede leer el archivo"); return 0; } fgets(tam1,sizeof(tam1), txt1); double c = atof(tam1); printf("%f",c); when I debug: tam1 is...

Raspberry Pi: printf() doesn't work with wiringPi

c,printf,raspberry-pi,gpio
I'm trying a simple code that using wiringPi as here: #include<wiringPi.h> #include<stdio.h> int main(void){ int i; wirintPiSetup(); pinMode(0,OUTPUT); //a single LED pinMode(8,INPUT); //tactile switch for(;;){ delay(500); //push tactile switch and LED is turning on if(digitalRead(8)) digitalWrite(0,0); else digitalWrite(0,1); printf("%d",digitalRead(8)); } } I expected a result of printf() is output to...

Return value of fprintf

c,printf,fwrite
#include <unistd.h> #include <stdio.h> #include <errno.h> #include <string.h> int main(void) { FILE *fh = fopen ("file.txt", "w"); if (fh != NULL) { int i = 0; while(i < 5){ if (fprintf (fh, "%s", "hello") < 0) { fprintf (stderr, "err=%d: %s\n", errno, strerror (errno)); } if(ferror(fh)) { printf("wrong\n"); } sleep(10);...

Please explain this output of the code

c,function,return,printf,scanf
#include<stdio.h> int GetPositiveInt(void); int main(void) { int num = GetPositiveInt(); printf("%d",num); return 0; } int GetPositiveInt(void) { int n; do { printf("Enter a positive number : "); scanf("%d",&n); }while(n<=0); } The output is the value of n but I don't know how it is returned to num. Does scanf() and...

How to display multiple leading zeros for floating point values in C++? [duplicate]

c++,stream,printf,double,stringstream
This question already has an answer here: How can I pad an int with leading zeros when using cout << operator? 6 answers In a C++ program, I want to display a column of floating point values so that the sign, digits, and decimal point all line up. Multiple...

Printing a line read from a file containing a particular word

c,pointers,file-io,printf,free
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int i, p=0;; int c; char file_name[100]; char search[10]; printf("Enter the file name:"); scanf("%s", file_name); printf("Search word:"); scanf("%s", search); FILE *f = fopen((strcat(file_name, ".txt")), "rb"); fseek(f, 0, SEEK_END); long pos = ftell(f); fseek(f, 0, SEEK_SET); char *bytes = malloc(pos + 1);...

Inserting arguments into string

php,string,insert,printf
In PHP, inserting variables into a string can be done by using sprintf. If I have two string variables $a and $b, they can be inserted into another string like this: $string = sprintf("String containing %s two other strings %s", $a, $b); Is there a function such that the string...