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 8 years ago.
Improve this question
code isnt working on line 19 & 20
i'm trying to get a string named hotel...
when i put gets(hotel) almost over everything surprisingly code starts working...but not in the middle of the code.!!!!!
#include<stdio.h>
main()
{
char topping[24];
char hotel[50];
int slices;
int month,day,year,i;
float cost;
printf("how much a pizza cost in your area? ");
printf("enter in $XX.XX\n");
scanf("$%f",&cost);
printf("what is your favorite one word pizza topping?\n");
scanf("%s",&topping);
printf("how many slices of %s of pizza \n",topping);
scanf("%d",&slices);
printf("which is your favorite hotel in town?\n");
gets(hotel);
printf("what is today's date (enter in XX/XX/XXXX format)\n");
scanf("%d/%d/%d",&day,&month,&year);
printf("\n\n\n\n\nwhy not treat yourself %d slices of %s pizza in %s on %d/%d/%d it will cost you only %.2f",slices,topping,hotel,day,month,year,cost);
return 0;
}
This is the same thing I talked about recently here: D lang - Using read and readln() in the same program although in C instead of D so the solution is slightly different but same explanation.
The scanf stops on whitespace, which is a newline... which gets sees as the end of input and thus reads an empty line.
The solution is to consume that newline before continuing:
printf("how many slices of %s of pizza \n",topping);
scanf("%d",&slices);
fgetc(stdin); // ADDED THIS LINE TO READ PAST THE NEW LINE CHARACTER
printf("which is your favorite hotel in town?\n");
gets(hotel);
PS don't use gets, use fgets(hotel, 50, stdin); instead. The 50 there is the size of the buffer, ensuring it doesn't overflow.
There are a couple of things I would change.
When you are reading topping & hotel, they are strings, you do not need to pass that by reference. So pass scanf("%s", topping);
When you are doing the strings, you want to make sure you don't allow the user to overfill the array. See this for an example of how to limit the input size.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
Here I am entering my name Amir but is printing weird character É
My code:
#include<stdio.h>
int main()
{
char Name[64];
printf("Enter first name: ");
scanf("%c", &Name);
printf("%c", Name);
}
Source: https://i.stack.imgur.com/qfcUD.png
Few things to fix here.
Firstly, use the correct format specifiers for printing values. %c deals with a character. To print a string you need to use %s.
If you must use scanf then following should work well unless user enters 64 or more characters.
scanf("%s", Name);
printf("%s", Name);
However, it is highly recommended to avoid using scanf to get strings as user input. Use fgets instead.
fgets(name, 63, stdin);
printf("%s", name);
I recommend you to read the man page for fgets(), but in a nutshell, the benefit of using it over scanf is that it prevents array overrun (array out of bounds).
I'm in my first steps in C programming, and I came across a task I can not find a solution to.
The task is simple: taking a character from the user.
After that, you receiving a string from the user until the user types the * character.
Then print the number of times the user typed the first character.
I was able to solve the problem using char [SIZE]ת when I placed a maximum input size of 255 bytes (#define SIZE 255).
Nevertheless, my teacher tells me that although the solution is working well, this was not the purpose of the exercise, also, I can not assume a maximum string size.
He asks us to use the input buffer.
No dynamic memory allocation is used in the exercise, and only the stdio.h library is allowed.
I read a lot about the input buffer, but I still have not found the possibility to solve the exercise - how can I absorb value from the user without knowing its size?
I would be happy to receive assistance and tips on how to use the input buffer correctly.
Or more focused, how to input values (string of characters) into the input buffer, and then go over each character separately in this string and process it.
Thank You
There is no need to store all characters. Once you have read a character you can throw it away and just increase a counter. Something like this:
#include <stdio.h>
int main() {
char c, first;
int counter=0;
printf("Enter first character: ");
scanf("%c", &first);
do {
scanf("%c", &c);
if(c == first)
counter++;
} while (c != '*');
printf("You entered '%c' %d times\n", first, counter);
}
Output:
Enter first character: a
aaaaa*
5
or
Enter first character: a
aabbaa*
You entered 'a' 4 times
Note:
As been pointed out in the comments, scanf is not a good tool for this kind of stuff. I would advice against the usage of it, unless you know it is the right tool. But that's beside the point. The point here was to show you that you don't need to store the whole input buffer. If you want to look at alternate input methods (as William Pursell suggested in the comments) you could have a look at fgetc, getc, or getchar for reading single characters. fread is also a tool you should get familiar with.
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 6 years ago.
Improve this question
I'm trying to display the users answer for input answer2 but it's only displaying the first word of the complete input sentence.
#include <stdio.h>
int main()
{
char answer[20];
char answer1[20];
char answer2[100000];
printf("What is your first name \n");
scanf(" %s",answer);
printf("What is your favorite color \n");
scanf(" %s",answer1);
printf("What is your quest \n");
scanf(" %s",answer2);
printf("Your name is %s,Your favorite color is %s,and your quest is s %s",answer,answer1,answer2);
return 0;
}
Screenshot of Program running
%s with scanf() stops scanning upon encountering a whitespace. So, you cannot use that to scan multiple words.
Quoting the standard, for %s conversion specifier, with scanf()
s Matches a sequence of non-white-space characters.
So, it will scan until it founds a whitespace in the input. An input with multiple words (separated by whitespace) will not be completely scanned, only the first word will be scanned and stored.
Instead, a better approach will be using fgets() to to scan the input containing whitespaces, then strip off the trailing newline and tokenize (if required).
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 6 years ago.
Improve this question
First, I want to make clear that I'm a beginner and this might be a silly question and that I'm probably doing something wrong.
I want to read characters from a string until a , is found and store them in another string. I also want to know how many characters have been read. This is what I'm doing with sscanf:
sscanf(str, "%[^,]s %n ", newstr, &number);
When I try to print number it prints 0 regardless of my input, even when several characters were stored in newstr.
The problem seems to be in the [^,] sub-specifier as %n works as it should without it.
I want to read characters from a string until a ',' is found and store them in another string. I also want to know how many characters have been read.
The s is not needed. It is not part of the "%[^,]" specifier. Also the trailing " " serves no purpose. Should limit input length too. Do not use newstr unless code knows it was filled.
char str[100];
int number = 0;
// sscanf(str, "%[^,]s %n ", newstr, &number);
sscanf(str, "%99[^,], %n", newstr, &number);
if (number) Success();
else Fail(); // do not use newstr
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
We got an assignment to make a program to read what is written inside our text file (name, student number, course, year, section, etc.. etc..) But I can't seem to make it work, can you tell me what's wrong?
#include <windows.h>
#include <conio.h>
#include <stdio.h>
struct record
{
char name[50],number[50],course[50],gender;
int year, section;
float midterm,final,average,sum;
};
int main()
{
int a=1,n;
int passed=0,failed=0;
FILE *fp;
fp = fopen("BSU.txt","r");
if(fp==NULL)
{
printf("ERROR!");
getch();
}
struct record student[25];
printf("Please input the number of students: ");
scanf("%d", &n);
for(a=0;a<n;a++)
{
fscanf(fp, "%f", student[a].average);// I CANNOT MAKE THE FSCANF WORK!!//
}
getch();
}
It should be
fscanf(fp, "%f", &student[a].average);
instead of
fscanf(fp, "%f", student[a].average);
But this allows you only to read a file containing numbers, for example:
1.5
1.9
2.7
The file you want to read is more compilcated.
So in your for loop you need to read 10 lines, extract the relevant information from each line, store that information in the corresponding field of your record, and store the record somewhere.
You need to consider the input file format.
When you're calling fscanf the 'cursor' is located at the first line of your file. What you need to to is to bring the cursor to the line you want to read.
Student Name: Andrea Zoelle Jacinto <-- cursor is located at the beginning of this line
Gender: M
Student Number: 2015-04711-MN-0
Course: BSIT
Year: 1
Section: 2
Midterm Grade: 2.00
Final Grade: 1.75
Average Grade: 1.8 <-- you need the cursor here
To achieve that you can use fgets in an while loop to get rid of the lines before the desired line.
char line[256];
while( fgets(line, 256, fp) && line[0] != 'A'); // line[0] != 'A' makes the loop stop when it reached the desired line
Now your cursor is at the desired line, however you need to get rid of the text in front of the value you want to read.
Average Grade: 1.8 <-- get rid of "Average Grade: "
The good thing is line already contains this line, so you can use sscanf to read formatted from this string.
sscanf(line, "%*s %*s %f", &student[0].average); // note the ampersand in front of student[0].average to get its address
Using %*s makes sscanf ignore the words "Average" and "Grades:" so %f will read the desired value.
Because it looks like your homework, I will not give you the solution but I tell you where is bug.
You are using fscanf in the incorrect way. This line:
fscanf(fp, "%f", &student[a].average);
is telling something like: "take somevalue (float type) and write it to student[a].average".
It can't work in your situation, because your data structure is more compilacted.
What have you to do?
First, try to write all data from the file on output.
After that, you should try to parse the line which are you interest :)
Read about getline, sscanf. It could be very helpful for you :)