Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Right so i have a program that will find a strings place in a file, and the line it belongs to. Now the Find works fine but the string compare has a big problem i cannot get my head around, here is the code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(void){
int loop, line;
char str[512];
char string[512];
FILE *fd = fopen("Student Passwords.txt", "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
printf("Enter the string: ");
scanf("%s",string);
printf("Enter the line number to read : ");
scanf("%d", &line);
for(loop = 0;loop<line;++loop){
fgets(str, sizeof(str), fd);
}
printf("\nLine %d: %s\n", line, str);
str[strlen(str)-1] = '\0';
if(strcmp(string,str) == 0 )
{
printf("Match");
}
else
{
printf("Nope");
}
fclose(fd);
getch();
return 0;
}
Someone told me to use strlen, which i of course inserted into the code but i think it just makes it worse, i am not sure what to do now can i have some help?
Text file:
Password
abcdefg
Star_wars
jedi
Weapon
Planet
long
nail
car
fast
cover
machine
My_little
Alone
Love
Ghast
Thanks
Edit: Input: Random word , Input: line number. Program will go to the line chosen and scan the string stored there, and compare it with the input string. Output: Either Match or Nope.
Edit: Input: Password, 1 Output: Match , Input: Password, 2 Output: Nope.
Your program works fine for me except that your text file have trailing spaces after some words. but your user input do not have spaces. Try to print the lengths of the user input and read line and you can find out.
Remove all trailing spaces from your text file and there should not be any problem.
Also as others have mentioned, it is good to use similar input functions in your code. you can use fgets for user input also.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
#include<stdio.h>
int main()
{
char str(100);
int i;
printf("Please enter your name")
scanf("%s",str);
printf("your name");
return 0 ;
}
This is the code I have written,
but the problem is the code runs but never gives the output
until I manually stop the code.
How does the scanf("") function work?
Scanf reads formatted input from the standard input. There is nothing wrong with scanf itself. Your way of using it is also correct, but there are two problems with your code:
The first is that arrays must be defined with []. Therefore,
char str(100);
should be
char str[100];
The second problem is that you are receiving the input, but you are never printing it. To do so, you can write the following code:
printf("%s\n", str);
The final code being:
#include <stdio.h>
int main()
{
char str[100];
printf("Please enter your name");
scanf("%s", str);
printf("your name is: %s\n", str);
return 0;
}
Also, don't forget the semi-colons.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
#include<stdio.h>
int main()
{
char word[1000];
scanf("word%s", word);
printf("%s", word);
}
It seems that when I input any string, as long as I type out "word" first, I get proper output.
But is this program actually valid
It compiles and therefore is valid from a syntax perspective. It's also fine in order to check that a prefix is used.
However, there are at least two ways to get undefined behaviour:
scanf might store more than 1000 characters (read 999 and one for the final \0)
scanf might read none if the input does not start with "word"
You should therefore check the result of scanf, initialize word, and also limit the maximum number of characters that scanf reads:
#include<stdio.h>
int main()
{
char word[1000] = {0};
int ret = scanf("word%999s", word);
if ( ret == 1 ) {
printf("%s", word);
}
}
this program is valid ,but you have to be careful about buffer overflow , which means if user input more than 999 chars this will lead to undefined behavior , so I suggest this:
scanf("word%999s", word);
also as you said as long as I type out "word" first ,otherwise char word[1000] will be uninitialized.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
How would I read information from a file to variables if I don't know how long it's gonna be.
Example of file:
student name
class grade credits
class grade credits
class grade credits
How would I save this info from this file if the number of classes varied. I need to print this information to the screen, while using the grades and number of credits to calculate a students GPA.
As proposed by fluter, fgets will allow you read the file line by line. getline is another (better IMHO) solution, it's manpage provides a simple usage example.
Then inside the reading loop, you have several options. I suggest you sscanf applied on the line read.
It returns the number of items read. In this kind of simple case, I usually try to scan the line with different format strings and check the number of items read to verify if the line matched.
For example, you could use something like:
"%s" as the format string for student name lines
"%s %c %d" as the format string for grade lines
And I suggest you to compute the GPA inside the loop, this way, you shouldn't have to store the grades, if I'm correct.
The usual way to do is to scan the input file until it meet the end of file or EOF, so you know you have reached the end of the file.
Something like this:
FILE *fp = fopen("grade.txt", "r");
if (!fp) { exit(1); }
char line[1024];
char name[1024];
char *s;
s = fgets(line, sizeof line, fp);
if (!s) { fclose(fp); exit(0); }
strcpy(name, line);
do {
s = fgets(line, sizeof line, fp);
// convert line to grade, to integer or double as you want
} while (s != NULL);
// compute the GPA
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a project for school and in it, I need to get a four digit number and then continue immediately with no enter. For example: "Enter a number: 1424" and then it just continues, and you can't enter anymore numbers, aw well as Enter key pressing should not be needed.
I tried scanf("%4d",&num); but it waits for Enter key.
And one more restriction is... I can't use strings in this project, so all the solutions must be without strings.
The only way to organize input without Enter key press are functions getch and getche from conio.h header, that I suppose is not in C/C++ standard. So POSIX standard names are _getch and _getche.
With that functions you will read character - which are not strings if you process each char separately.
UPDATE:
My solution is:
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main(void)
{
char ch; // to store an input - single char
int number = 0; // to make number from inputs
printf("Enter a number: ");
int digits_cnt = 0;
while (digits_cnt < 4)
{
ch = _getche();
if (isdigit(ch))
{
number *= 10; // add an order to number
number += ch - '0'; // add a decimal digit to number
digits_cnt++; // count this digit to stop loop
}
}
// just to check result
printf("\nThe number %d was entered.\n", number);
return 0;
}
I assume that all 4 digits should become a number, but, perhaps, you need to do something else with them.
For reading 4 digits you probably want use char * fgets ( char * str, int num, FILE * stream ); that will do exactly what you are asking for. You should not use scanf for interactive input you can find why in this article
To the string part since you are typing input in ascii you are already working with strings(arrays of chars).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to get the integers values to be passed to a linked list from a text file.
The problem is that the text file is structured as columns and rows.
This is an example below regarding the text file:
5:0:3
4:1:2
3:1:1
4:2:2
3:3:1
How can I get these values? Noting that my program should notice the : and not only the EOF. I wrote a similar program but it can't take care of the colon. it only scans the integer values until the EOF.
You can use fgets() to read lines and then sscanf() to parse each line. If the lines, contain only 3 integers then it can be done as:
int i, j, k;
char str[256];
FILE *fp = fopen("filename", "r");
if(!fp) {
/* File opening error */
}
while(fgets(str, sizeof str, fp)) {
char *p = strchr(str, '\n');
if (p) *p = 0; // remove the trailing newline, if
if( sscanf(str, "%d:%d:%d", &i, &j, &k) == 3) {
printf("%d %d %d\n", i, j, k);
/* do processing with i, j & k */
}
else {
/* failure */
}
}
You can use fscanf as
fscanf(fp, "%d:%d:%d", &var1, &var2, &var3);
You can read in the entire line as a string using getline.
Then you can use the string function find() to find the :
After that you'll have saved in what position in the string the : was found, and you can convert the character that is one position behind the : into a integer using atoi(). That works for the first 2 numbers.
For the last number, you do the same thing but instead of : you look for a space.