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.
Related
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 3 years ago.
Improve this question
I tried to write a program which takes a line from user (console) until a comma, full stop or newline character is encountered and tell how many characters read following the specific pattern.
The string is read correctly but the count is not accurate.
#include <stdio.h>
int main()
{
int n;
char s[100];
// The following line should read a string until (. or , or new-line in encountered)
// and %n should tell me the no of characters it read until that point
scanf("%[^.,\n]s%n", s, &n);
// The String in okay
printf("%s\n", s);
// But count of characters read is 0
printf("%d\n",n);
return 0;
}
5 problems:
The "s" in "%[^.,\n]s%n" stops scanning as there can be no 's' read after %[^.,\n]. %[^.,\n] would have read in all 's'. Thus the later "%n" never occurred and the n that was later printed, a 0, was bad code - printing the uninitialized n - which could have been any int or a trap.
Scan lacks a width limit. Bad things happen after the 99th character.
With scanf("%[^.,\n]s%n", s, &n);, scanning will saving nothing in s if the first character is a .,\n. Later printing of s is bad as s[] is uninitialized.
Code fails to check the return value of scanf().
scanf() does not certainly read a line as directed with "write a program which takes a line from user" - it stops short using scanf().
C Std Lib defines a line as below, so code should attempt to read the entire line.
A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character.
scanf() alternative
int n = 0;
char s[100];
s[0] = '\0';
int cnt == scanf("%99[^.,\n]%n", s, &n);
if (cnt == EOF) puts("Nothing was read");
else printf("%s\n", s);
Better alternative
I'd recommend using fgets() instead of scanf(): takes a line from user.
char s[100];
if (fgets(s, sizeof s, stdin)) {
size_t n = strcspn(s, ".,\n"); // offset of string that does not have .,\n
s[n] = '\0';
printf("%s\n", s);
printf("%zu\n", n);
}
Note: Lines longer than about 100 need additional code.
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 4 years ago.
Improve this question
I'm working on a project and I want my program to read a strictly 5 digits number with a leading zero.
How can I print the number with the leading zero included?
Plus: how can I provide that my program reads 5 digits including a zero as a leading number?
I assume you want to read in int variable. If so you can try the below solution.
#include<stdio.h>
void main()
{
int a;
scanf("%5d", &a);
printf("%05d",a);
}
The best way to have input under control is to read in a string and then parse/analyze the string as desired. If, for example, "exactly five digits" means: "exactly 5 digits (not less, not more), no other leading characters other than '0', and no negative numbers", then you could use function strtol, which tells you where number parsing has ended. Therefrom, you can derive how many digits the input actually has:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char line[50];
if (fgets(line,50,stdin)) {
if (isdigit((unsigned char)line[0])) {
char* endptr = line;
long number = strtol(line, &endptr, 10);
int nrOfDigitsRead = (int)(endptr - line);
if (nrOfDigitsRead != 5) {
printf ("invalid number of digits, i.e. %d digits (but should be 5).\n", nrOfDigitsRead);
} else {
printf("number: %05lu\n", number);
}
}
else {
printf ("input does not start with a digit.\n");
}
}
}
use printf family with '%05d" to print number with leading zeros. use sscanf to read this value (leading zeros are ignored).
Consult the following code:
int a = 25;
int b;
char buffer[6];
sprintf( buffer, "%05d", a );
printf( "buffer is <%s>\n", buffer );
sscanf( buffer, "%d", &b );
printf( "b is %d\n", b );
output is:
buffer is <00025>
b is 25
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 want to read n integers from user during execution and the numbers are separated by spaces. It would be the best to be received as an array. For input 1 22 3 445 3, the result is, array[0]=1, array[1]=22 and so on. I have to do it in C. Can't use
scanf("%d %d %d", &var1, &var2, &var3);
because, I don't know how many such numbers would be inserted. The value of n would be read from user just before reading this data.
enum { MAX_NUMBERS = 1000000 }; // Choose appropriate upper bound
int n;
if (scanf("%d", &n) == 1 && n > 0 && n < MAX_NUMBERS)
{
int array[n];
for (int i = 0; i < n; i++)
{
if (scanf("%d", &array[i]) != 1)
…process error — terminate loop?…
}
…use array…
}
You can read multiple numbers with scanf() using a loop as shown. You've no idea whether they were all presented on a single line, or each was on its own line, or whether there were many blank lines between successive numbers (or any permutation of all these possibilities).
The scanf() family of functions basically do not care about newlines — it is hard to force them to do so. When you care about line-based input, use fgets() or POSIX function getline() to read a line and sscanf() — or other string parsing functions — to process the line.
I'm assuming support for C99 with VLA (variable length arrays). The principles are the same without that support — the mechanics are a little different (and there are multiple options for how to do it).
Use fgets() and then strtok() with atoi().
Take the numbers as a string.
Here is one way to do it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char numbers[100];
int myn[100];
printf("Give me numbers..\n");
fgets(numbers,100,stdin);
const char s[2] = " ";
char *token;
token = strtok(numbers, s);
int i=0;
myn[i]=atoi(token);
while( token != NULL )
{
i++;
printf( " %s\n", token );
token = strtok(NULL, s);
myn[i]=atoi(token);
}
printf("You gave me: ");
for (int j=0; j<i; j++){
printf ("%d, ", myn[j]);
}
return(0);
}
The above C program does exactly what you want. At the for loop, it prints to the screen the numbers you gave from keyboard. The "problem" would be much easier by using enter instead of spaces between the numbers.
Click on the links, to see very useful details about the functions used.
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.