Reputation: 265
I have written a simple method that gets the input from a long string and prints it. I save my data in a char array and try to set the last element of said array to '\0' for null termination so that I may printf(%s,array).
#include <stdio.h>
#define MAX 9
#define DEBUG 1
int QUIT = 0;
int assignNewBoard(void);
void main (int argc, char *argv[]) {
assignNewBoard();
}
int assignNewBoard(void) {
int row,col , count=0,maxCount=(MAX*MAX);
char ch;
char input[maxCount+MAX]; //our buffer with room for overflow.
//Hopefully never more than 90chars.
while((ch = fgetc(stdin)) != '\n') {
//input checks
if(feof(stdin)){
if(DEBUG) printf("Finished!\n");
QUIT = 1;
}
count++;
input[count] = ch;
}
if(DEBUG)printf("::");
input[count+1] = '\0'; //null termination for printing.
printf("%s\n",input);//This doesn't seem to happen at all in output!
if(DEBUG) printf("We got %d count!\n", count);
return 0;
}
But the above code does not print my char array as a string! Just prints empty after the :: in console! So what am I doing wrong here? I had it working like this at one point in my code but now it isn't, not even in simplified file!
When run this should have a line "::(input)" but the line is simply "::" instead.
I am using GCC to compile.
Upvotes: 0
Views: 1318
Reputation: 101
Why you want to do all that..You can simply do it this way. Scanf string till \n and print it.
#include<stdio.h>
int main(){
char str[90];
scanf("%[^\n]",str);
printf("%s",str);
return 0;
}
Upvotes: 2
Reputation: 141544
You increment count
before doing anything with it, so the first character you read goes into input[1]
. Array indices start at 0
in C; the value of the first character in the array, input[0]
, is garbage and so the output you get may vary from time to time. (The behaviour is undefined).
You should also specifically check that count
never gets so big that you run off the end of the buffer. If that does happen then it may cause your program to crash elsewhere and these errors can be difficult to debug.
Upvotes: 4