Looking to read in using scanf but I want to stop reading if I encounter a ',' '\0' (newline) or EOF
I'm not really sure how to stop achieve this.
I was using
char * aBuff;
char * bBuff;
char * cBuff;
//read in the first three lines and put them into char arrays
//while (scan() != (',' || '\0' || EOF)) //was trying to put it into a while loop, wasn't sure
scanf("%s", aBuff);
scanf("%s", bBuff);
scanf(%s, cBUff);
I plan on taking the input and putting them into separate arrays. Basically take input until a , or new line and place that data into an array and continue this process until the end of file.
scanf() is not a practical method to read until encountering ',', '\0', or EOF. Use fgetc().
The biggest problem is specifying '\0' in the format of scanf(). Example: with format "%[^,\0]", scanf() only reads "%[^," as it stops at the embedded '\0'. So with an invalid format specifier --> undefined behavior.
size_t ReadX(char *dest, size_t size) {
size_t len = 0;
if (size) {
while (--size > 0) {
int ch = fgetc(stdin);
if (ch == 0 || ch == ',' || ch == EOF) break; // maybe add \n too.
*dest[len++] = ch;
}
*dest[len] = '\0';
}
return len; // or maybe return the stopping ch
}
scanf() could be use if code used the ponderous:
scanf("%[\1\2\3...all_char_codes_min_char_to_max_char_except_,_and\0]%*c", &s);
You can try using scansets
scanf() should stop on EOF, but you'd want to maybe do something like this:
scanf("%[^,\0]", &s);
Related
int main(void)
{
char ch;
int len = 0;
printf("Enter a message: ");
ch = getchar();
while (ch != '\n')
{
len = len + 1;
ch = getchar();
}
printf("Your message was %d characters long\n", len);
return 0;
}
I understand the first " ch = getchar(); " because that's reading the characters from the printf statement, but I don't understand the purpose of the 2nd " ch = getchar(); " in the while loop.
This is trying to loop on reading characters until a newline is read, and it's just doing it in an odd way: normally I'd expect to see just one getchar() as part of the loop itself.
This would be a more customary way to write the same thing:
#include <stdio.h>
int main(void)
{
int ch; // note: not char!
int len = 0;
printf("Enter a message: ");
while ( (ch = getchar()) != EOF && ch != '\n')
len++;
printf("Your message was %d characters long\n", len);
return 0;
}
We see a few changes here.
First, we see the ch = getchar() assignment in the loop condition itself: fetch a character, and as long as we're not done (however defined), keep going and keep counting.
But we also have to check for EOF - end of file - which signifies the end of input, so that test is done here as well. If you fail this test, the code will loop and loop and loop and loop because it will never get EOF. Always check for end of file!
IMPORTANT: You really must use an int variable to receive the return from getchar(), not a char. Surprise! The reason is that EOF is typically -1 (EOF must be negative), and getchar() returns either EOF or the next 'character as an unsigned char converted to an int' (normally, a value 0..255). That is more values than can be stored in a plain char, so it is crucial to use an int instead of a char variable so you can be sure to detect EOF properly.
Also a trivial simplification of len++ for len = len + 1.
The original loop is doing more or less the same thing, but without combining the get + check parts into one.
To get all the characters that are typed before pressing enter.
getchar reads only one character at a time.
The second ch = getchar reads one character, but it is inside of a while loop so getchar()will be read characters from input, one by one, until a line-break appears in the input. If you put in the input a string like this "Hello World" and press enter your program will read "Hello world\n" then the while loop increase by one the variable len to count the characters which you putted in the input and when getcharreads '\n' the while loop will end and the printf()shows you the length of your string
struct Demo{
char a[50];
char b[50];
int a;
};
Can anyone give the code for this structure Demo where a and b will contains string with different words[white-spaces].
I tried
scanf("[^\n]s",name.a); //where name is the object
fgets(name.a,50,stdin);
Note : we can't use gets method as well
So, If any other method is there, please provide me.
To read a line of user input into char a[50]; with its potential trailing '\n' trimmed:
if (fgets(name.a, sizeof name.a, stdin)) {
name.a[strcspn(name.a, "\n")] = '\0'; // trim \n
}
Work is needed to cope with consuming excessive long input lines and using the last element of name.a[] such as:
// Alternative
if (scanf("%49[^\n]", name.a) == 1) {
// consume trailing input
int ch;
while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
;
}
} else { // Handle lines of only \n, end-of-file or input error
name.a[0] = '\0';
}
The scanf("%49[^\n]%*c", name.a) approach has trouble in 2 cases:
1) The input is only "\n", nothing is saved in name.a and '\n' remains in stdin.
2) With input longer than 49 characters (aside from the '\n'), the %*c consumes an extra character, yet the rest of the long input line remains in stdin.
Both of these issues can be solves with additional code too.
I am trying to switching my use of getchar to fgets but, when using getchar, the entire code does not work.
//fgets(line, sizeof(line), stdin);
while(fgets(line, sizeof(line), stdin))
{
portNum[sizeof(line)] = (char)line;
}
while((c = getchar()) != '\n')
{
portNum[num++] = c;
}
portNum[num] = '\0';
How can I make equal for those two functions to work properly?
You usage of fgets is wrong.
fgets Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
In your case fgets will read all the characters until newline is encountered.
Also, the parameters usage is wrong.
char * fgets ( char * str, int num, FILE * stream );
str => Pointer to an array of chars where the string read is copied.
num => Maximum number of characters to be copied into str (including the
terminating null-character).
stream => Pointer to a FILE object that identifies an input stream.
stdin can be used as argument to read from the standard input.
Refer to the fgets documentation for more information.
fgets man page
OP's fgets() usage is unclear and portNum[sizeof(line)] = (char)line; is certainly in error.
Instead: how to make the below getchar() code more fgets()-like:
// assumed missing code
#define N 100
int c;
char portNum[N];
size_t num = 0;
// size and EOF detection added (which should have been there)
while(num + 1 < sizeof portnum && (c = getchar()) != '\n' && c != EOF) {
portNum[num++] = c;
}
portNum[num] = '\0';
// assumed missing code
if (c == EOF && num == 0) Handle_EndOfFile_or_InputError();
else ...
This can be replaced with fgets() code
#define N 100
char portNum[N+1]; // 1 larger for the \n
if (fgets(portNum, sizeof portNum, stdin)) {
// lop off potential trailing \n
portNum[strcspn(portNum, "\n")] = '\0';
...
} else {
Handle_EndOfFile_or_InputError();
}
I know I can get the first character of a line of standard input by using getchar(), but I only want the first character of each line. Is there a function I can use to get rid of the rest of the string entered into standard input (if it is more than one character)? if not, what methodology should I consider using to get rid of the rest of the standard input line?
char buf[100];
while(fgets(buf,sizeof(buf),stdin) != NULL)
{
if(strlen(buf)>0)
buf[1] = '\0';
printf("%s",buf);
}
Read the whole line using fgets() and just nul terminate it after the first character.
#include <stdio.h>
int main(void)
{
int ch;
size_t len;
for (len = 0; 1; ) {
ch = getc(stdin);
if (ch == EOF) break;
if (!len++) putc(ch, stdout); /* the first character on a line */
if (ch == '\n') len = 0; /* the line has ended */
}
return 0;
}
Please note that the first character on a line can actually be a '\n' !!!
// Get the character you need
char c = getchar();
// Skip the rest
int a;
while((a = getchar()) != '\n' && a != EOF);
If you know how many lines you'll have, you can put it in a loop.
How do I tell my program how to vary how many elements are to be read by scanf? I want it to read each character in a string, and the length of the string may vary from one character to a hundred characters. I know I can do scanf("%c%c%c%c...") a hundred times but is there an easier way to do this?
Sure, use fgets() with an appropriately sized buffer:
char buf[LINE_MAX];
if (fgets(buf, sizeof buf, stdin) != NULL) {
// input is now in `buf'
}
If you really can't use arrays, then call getchar() until it finds a newline:
int sum = 0;
int ch;
while ((ch = getchar()) != EOF && ch != '\n') {
sum += ch;
}
(this already does what you want, i. e. it sums the character codes of the string the user enters.)
You can do this way
char A[105];
scanf("%s", A);
printf("%s\n", A);
By this, you can input string with various length. If you input "abc" then the result is "abc"