C: Wrong Characters with Second fgets - c

I have this code:
char temp;
scanf("%c",&temp);
fgets(variable1,50,stdin);
strtok(variable1, "\n");
printf("%s ", variable1);
This gets a string with the possibility of having spaces and assigns it to the variable variable1. Later, I can print the string with no problem.
The problem comes when I add to code other fgetsfor gets other string in other variable.
if (1) {
scanf("%c",&temp);
fgets(variable2,50,stdin);
strtok(variable2, "\n");
printf("%s ", variable2);
}
The result complete is:
char temp;
scanf("%c",&temp);
fgets(variable1,50,stdin);
strtok(variable1, "\n");
printf("%s ", variable1);
if (1) {
scanf("%c",&temp);
fgets(variable2,50,stdin);
strtok(variable2, "\n");
printf("%s ", variable2);
}
variable1 always works correctly. But I try print in some phrases with %s variable2 but the result does not get the first character, only in second scanf. If I put HELLO, variable2 is ELLO.
I have tested using another temp variable, another data, etc. But always get the same error.
Why is this happening?
UPDATE
For more information. I use scanf because, if I do not use it, the program does not pause while waiting for the string. I use strtok(variable1, "\n"); to remove the line break.
This program is inside a while and in switch case. I put the complete code:
case 4: printf( "Put equipo: ");
scanf("%c",&temp);
fgets(equipo,50,stdin);
strtok(equipo, "\n");
if (Exists(equipo)) {
printf("Put Piloto ");
scanf("%c",&temp);
fgets(piloto,50,stdin);
strtok(piloto, "\n");
printf("You said %s and %s", equipo, piloto);
}
break;
If I introduce like Equipo HELLO and like Piloto FRIEND, the output is:
You said HELLO and RIEND

Re-written based on OP latest edits to post, and comments...
You describe the need to simply obtain two strings from user input, remove the newlines from each, then package both into a message to stdout. If this description actually matches what you need, change this code section:
...
scanf("%c",&temp);
fgets(equipo,50,stdin);
strtok(equipo, "\n");
if (Exists(equipo)) {
printf("Put Piloto ");
scanf("%c",&temp);
fgets(piloto,50,stdin);
strtok(piloto, "\n");
printf("You said %s and %s", equipo, piloto);
...
To this:
...
printf("enter equipo: ");
if(fgets(equipo, sizeof(equipo), stdin))
{
equipo[strcspn(equipo, "\n")] = 0; //remove newline
printf("enter piloto: ");
if(fgets(piloto, sizeof(piloto), stdin))
{
piloto[strcspn(piloto, "\n")] = 0;
printf("You said %s and %s", equipo, piloto);
}
}
...
Note: strtok(piloto, "\n"); works, but has problems if user just hits <return>
By the way, here are some other interesting ways to clear the newline

I do not understand your example code. Could you update the question with your actual code?
I assume scanf should not be there?
This code works fine for me:
char var1[50], var2[50];
fgets(var1, 50, stdin);
strtok(var1, "\n");
printf("Var1: %s\n", var1);
if (1) {
fgets(var2, 50, stdin);
strtok(var2, "\n");
printf("Var2 %s\n", var2);
}
Output:
Test1
Var1: Test1
Test2
Var2 Test2

Related

While loop still prints once after EOF in C

I have to look through a file and take out the information of a student. It all works fine so far, there are 21 lines in the file, the first 20 contain information of a student and the final line contains just a single name. For some reason my while loop continues, sees that there's no information after that last line and stops but it still prints out that last line of the file with other lines of information in the in the output as well.
count = 0;
while(fscanf(fp, "%d", &average)!= EOF )
{
if(fscanf(fp, "%d", &average)!= EOF ){
printf("\n/////////////////////////////////////////////////////////////////////////////");
fscanf(fp, "%s", name);
fscanf(fp, "%s", initial);
fscanf(fp, "%s", surname);
printf("\n\n\tName: %s \tInitial: %s \tSurname: %s\n", name, initial, surname);
fscanf(fp, "%d", &year);
fscanf(fp, "%s", coursename);
fscanf(fp, "%s", group);
fscanf(fp, "%d", &average);
printf("\n\tYear: %d \tCourse Name: %s \tGroup: %s \tAverage: %d\n", year, coursename, group, average );
printf("\n\tThis is entry number %d\n", count+1);
printf("\n/////////////////////////////////////////////////////////////////////////////");
count++;
}
if(fscanf(fp, "%d", &average) == EOF ){
printf("\n\nThank you for using the program\n\nAll of the student records are now displayed\n");
}
}
fclose(fp);
return 0;
}
If the second last line for instance was
Mike (M) Johnson 3 IT A 66
it would print that out perfectly fine but the final thing in the file the name "John" it would print out
John Johnson 3 IT A 66
I don't understand firstly why it wouldn't take Mike Johnson's initial and secondly when it shouldn't print that line to begin with? I've tried setting the if statements and while statement to take the name as the end of the file but I think when I use "%s" to find that at the begining it seems to skip everything to the next string in the file over by 1, so Mike's name would become (M), and so on.

printf is not working as expected. Can someone explain the output?

I am trying to read two strings from the keyboard and print them.
Why does printf("read 1st\n") run after the second scanf()?
#include <stdio.h>
int main(void)
{
char str[20];
char str2[20];
scanf("%s", str);
printf("read 1st\n");
scanf("%s", str2);
printf("read 2nd\n");
printf("str: %s\nstr2: %s\n", str, str2);
return 0;
}
Expected:
foo
read 1st
bar
read 2nd
str: foo
str2: bar
Actual:
foo
bar
read 1st
read 2nd
str:foo
str2:bar
I could not reproduce your problem, but adding a fflush(stdout); should take care of your problem.
scanf("%s", str);
printf("read 1st\n");
fflush(stdout); // Ensures that the above is printed before scanf is executed
scanf("%s", str2);
printf("read 2nd\n");
I would also change the scans to scanf("%19s", str);. Otherwise, bad things could happen if you enter a string longer than str can hold.

Cant read input line in C

Sorry for a stupid question, but this is really starting to annoy me.
I need to take a line of input from a console. Here's the relavent fragment of code:
int number_read=0;
char line[80];
printf("Enter register address: ");
number_read = scanf("%s\n", line);
printf("number of characters entered: %d; characters entered: %s.\n", number_read, line);
if (number_read > 0) {
<read some registers and display the results.>
}
It doesn't work. The "Enter register address" line is printed, and the cursor stops at the end of the line, and moves to the next line when I press enter, but then nothing else happens. I've tried replacing scanf() with fscanf(stdin,...), with fgets(stdin), gets, GNU's getline(), a short function that does the same thing, with diagnostics:
char *new_line, ch;
for(;;) {
ch = fgetc(stdin);
if(ch == EOF) break;
if((*line++ = ch) == '\n') break;
printf("Line so far: %s\n", line);
}
*line='\0';
I get the same response from all of them. I'm including all the requisite headers.
I'm on a Windows XP box, compiling with gcc 3.4.5 (mingw).
Can anyone see what I'm doing wrong?
In scanf you should use a %i to represent a int so, try with
scanf("%I", number_line);
The following code will works,
char buff_msg[1024];
while(1)
{
if(fgets(buff_msg,1024, stdin) != NULL){
printf("%s\n", buff_msg);
memset(buff_msg, 0, 1024); // you will need this line
}
}
You can
break the loop on your own condition
try read() it works in MinGW replace
this
number_read = scanf("%s\n", line);
with this also include #include<unistd.h>
number_read = read(STDIN_FILENO, (void *)line,sizeof line);
value scanf returns is not the number of strings in the number of elements to read(this case meybe 1).
Use the %n To get the number, such as desired.
scanf("%s%n", line, &number_read);
printf("number of characters entered: %d; characters entered: %s.\n", number_read, line);

Writing 2 strings on the same line in C

So I want to make the hello.c program write both the first name and the last name on one line so in this form but when I run my program in this current form it gives me the error "expected â)â before string constant" I think I have the rest of the code down because I have removed that line and ran it and it works. So I just want to ask how to get 2 strings that I have already pointed to to go on the same line.
This is my code
#include <stdio.h>
int main()
{
char firstname[20];
char lastname[20];
printf("What is your firstname?");
scanf("%s", firstname);
printf("What is your lastname?");
scanf("%s", lastname);
printf("Hello %s\n", firstname "%s", lastname);
printf("Welcome to CMPUT 201!");
}
You want
printf("Hello %s %s\n", firstname, lastname);
instead of
printf("Hello %s\n", firstname "%s", lastname);
#include<stdio.h>
#include<string.h>
int main()
{
char first_name[20] = " ", last_name[20] = " ", full_name[40] = " ";
printf("What is your firstname?\n");
scanf("%s", first_name);
printf("What is your lastname?\n");
scanf("%s", last_name);
sprintf(full_name,"%s %s",first_name, last_name);
printf("name is %s\n",full_name);
return 0;
}
I have shown the same using sprintf.
1) also in your program you are not returning anything, if dont want to return anything make it as void function. When you write int function, always make it an habbit to return the integer.
2) Also when you write the printf function always make it habit to add \n(new line) so the output looks good
happy coding.

Swap two words in a string using C programming

I am close to finish writing a program to swap two words inputed to a program. If i input "Billy Bob" the output will be "#\300_\377" Something weird like that... I believe there is something wrong with my scanf but not quite sure. Here is what i have so far..
{ int i,j,l;
char str[59];
printf("Enter the string\n");
scanf("%s", &str[59]);
l=strlen(str);
for(i=l-1; i>=0; i--)
{ if(str[i]==' ')
{ for(j=i+1; j<l; j++)
printf("%c",str[j]);
printf(" ");
l=i;
}
if(i==0)
{ printf(" ");
for(j=0; j<l; j++)
printf("%c",str[j]);
}
}
scanf("%s", &str[59]);
Writes the input at the end of the allocated space. Use the address of the first element:
scanf("%s", str);
but this will give you the first word, so either do:
scanf("%s %s", str1, str2); // str1, str2 are arrays
or use fgets:
fgets(str, 59, stdin);
Instead of using scanf("%s", &str[59]);, you could use gets(str);.
It works perfectly fine...
This is wrong:
scanf("%s", &str[59]);
//^not reading the str, str[59] is even out of bound
should be:
scanf("%s", str);
That way of writing the function is somewhat difficult to read. I'm not exactly sure what circumstances you are writing it in but an alternative solution would be to split up the input string by a token, in this case a space, and print out the two strings in the opposite order. An example of the function strtok() can be found here.
Something like this:
char str[] ="billy bob";
char * firstToken;
char * secondToken
firstToken = strtok(str, " ");
secondToken = strtok(NULL, " ");
printf("%s %s", secondToken, firstToken);
You're passing the first address after str to scanf. Change &str[59] to str.

Resources