This question already has answers here:
Correct way to read a text file into a buffer in C? [duplicate]
(8 answers)
Closed 7 years ago.
I want to make an array of characters and store the whole input in it(even if the input contains "\n" at some point. When i use:
char vhod[50];
fgets(vhod, sizeof(vhod), stdin);
it stores the input UNTIL the first newline. How to get the whole text in this array(including the text after the new line).
Example:
if my text is:
Hello I need new keyboard.
This is not good.
my array will only contain "Hello I need new keyboard.". I want to be able to read everything till the end of input a < input-1
I cannot use FILE open/close/read functions since it is input from keyboard.
While fgets() is designed to read up to a '\n' character or the specified number of bytes, you can use fread()1 instead, like this
size_t count = fread(vhod, 1, sizeof(vhod), stdin);
and count will contain the number of items read, which in this case is the same as the number of bytes since you are providing size 1 i.e. sizeof(char).
Note however that you must be very careful to add a terminating '\0' if you are going to use any function that assumes a terminating '\0'.
1Read the manual for more information.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
My book mentions that fgets will read until it meets the (n-1)th character or a character of a new line. By character of new line do we only mean Enter (\n)? I am asking this because what I did was to create a text file on which I started typing in some nonsense, surpassing the character limit of each line meaning that I used more than one lines. After that I used fgets and what I expected was it to read only the characters in the first line of the text file but what it did was read all of them.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char box[5000];
FILE *fp;
fp = fopen("test.txt", "r");
fgets(box, 5000, fp);
puts(box);
}
Test.txt (The text is random that's why it's silly) (285 characters):
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk25kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkggggggggggiiiiiiiiiiiiiiiiiiii
So the result I expected was for it to print only part of the text and actually as many characters as the limit that is set for one line, minus one, (which I think is something above 250). But instead of that, it prints all of them. Note: The same thing happens even I type even more characters in the file.
You seem to be assuming that there's an upper limit, perhaps 255 characters, on the length of a line in a text file. C imposes no such limit, except indirectly by using int as the size argument to fgets.
Your program defines a 5000-character array and calls fgets with a length argument of 5000. That means it can read a single line of up to 5000 characters (or close to that; I'm ignoring a couple of off-by-one issues for the '\n' and '\0' characters). The input line in your question is only 285 characters long, so your program will easily read it as a single line.
You can try changing the length of your array to see what happens when an input line is too long to fit:
char box[255];
...
fgets(box, sizeof box, fp);
Note that using sizeof box rather than repeating the number means the call won't get out of sync with the array size.
It only stops at the newline character \n or at n-1 characters. There is no newline character other than \n.
As you set the limit for your buffer and the amount fgets can read to 5000, it can easily read all the characters in your file and print them.
There is no line length limit in ISO C (ISO/IEC 9899), whether one is imposed by your book or not. Your book is probably outdated.
This question already has answers here:
Reading string from input with space character? [duplicate]
(13 answers)
Closed 6 years ago.
I want to get string elements with space. Let's say I have a string called test and user will enter something in every cell, for instance he will enter colors he will enter the colors in a single line like; Green Yellow Blue Black - then he will press enter then program take everything until the space entered and put it on the first element of string then continues. In this case the string should be according to;
test[0] "Green"
test[1] "Yellow"
test[2] "Blue"
test[3] "Black"
I have tried to write it with 2 nested loops but I couldn't manage to get strings with space
long i
char* test[4]
printf("Enter your guess:\n");
for(i=0;i<5;i++)
{
while(test[i]!=" ")
{
scanf("%s", test[i]);
}
}
That's because scanf (and family) with the "%s" format only reads space delimited words. To get a whole line you should use fgets instead.
Do note that fgets puts the ending newline in the buffer you provide (if it can fit)
Also, you definitely need to allocate memory for the strings first. The code you show seems to tell us that you don't initialize the array test which means you either have an array of null pointers (if test is a global variable) or have pointers being indeterminate (if test is a local variable. Both of these will lead to undefined behavior.
Depending on platform, you might have a function available called getline which allows you to read lines, and also allocates memory for you. As with fgets the ending newline will be added to the buffer.
Lastly, you can't compare string using the == operator, it will only compare the pointers and not what they point to. Therefore comparing using == will almost always be false, unless both pointers point to the same memory.
To compare string you should use the strcmp function.
This question already has answers here:
How can I read an input string of unknown length?
(11 answers)
Closed 7 years ago.
There are several ways how to retrieve string input, e.g getline() , or fgets() but all of them require size of the string as an argument. But what if i want to retrieve string of unknown size? How is it possible using getline() or fgets() in C?
The answer is no. You can't read a string of indeterminate length. You can, however, read one character at a time until you reach the size of the storage space you have allocated in your program. Use fgetc in a loop.
int fgetc(FILE *stream)
Open the stream , read one character at a time, and stop reading when you see your sentinel character, which is probably a newline.
So I am trying to read a defined number of characters from the input. Let's say that I want to read 30 characters and put them in to a string. I managed to do this with a for loop, and I cleaned the buffer as shown below.
for(i=0;i<30;i++){
string[i]=getchar();
}
string[30]='\0';
while(c!='\n'){
c=getchar(); // c is some defined variable type char
}
And this is working for me, but I was wondering if there is another way to do this. I was researching and some of them are using sprintf() for this problem, but I didn't understand that solution. Then I found that you can use scanf with %s. And some of them use %3s when they want to read 3 characters. I tried this myself, but this command only reads the string till the first empty space. This is the code that I used:
scanf("%30s",string);
And when I run my program with this line, if I for example write: "Today is a beatiful day. It is raining, but it's okay i like rain." I thought that the first 30 characters would be saved in to the string. But when i try to read this string with puts(string); it only shows "Today".
If I use scanf("%s",string) or gets(string) that would rewrite some parts of my memory if the number of characters on input is greater than 30.
You can use scanf("%30[^\n]",s)
Actually, this is how you can set which characters to input. Here, carat sign '^' denotes negation, ie. this will input all characters except \n. %30 asks to input 30 characters. So, there you are.
The API you're looking for is fgets(). The man page describes
char *fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
This question already has answers here:
Reading a C file, read an extra line, why?
(6 answers)
Closed 8 years ago.
I am trying to write a C program that is able to read data (strings) from a text file and swap each content in terms of bytes. I have already implemented the code and everything works just fine, and and I am able to read all the contents of the specified text file, but the problem is that the program is printing the last word from the text file twice and I do not know why? Any help will be helpful ! This is the code I have:
while( !feof(ptr_file))
{
//to read in group of words (sentences) if
//needed !.
fscanf(ptr_file, "%s", userName);
//time to swap letters of the word coming from the text file.
swap_a_word(userName, 0, 4);
swap_a_word(userName, 1, 2);
//new space.
printf("\n");
//display the word after swapping to the screen for the user.
printf("%s", userName);
}
The program must not print extra data. I do not know, but when the program reaches the end of the file, it prints the last data of the text file twice. Please any hints will be helpful !.
Thanks !
The problem is the while loop condition
while(!feof(ptr_file))
Note that EOF is preceded by a newline '\n'. fscanf returns the value EOF when the end of file is reached. However, this does not set the end-of-file indicator on the stream and as a result the loop is entered one extra time. You should check the return value of fscanf instead to find number of items successfully matched and assigned.