Is it possible to take a string and get two different values from it to store in different type variables, more specifically, an integer and a character.
Brief example:
string : "A - 3"
int number : 3
char name : 'A'
I've seen people take multiple int from a string but nothing worked for me. I should add I am very new to C, so I don't really know how to mess around with it too much.
Its for a slide puzzle minigame where I need to read a text file with all instructions from the user, formatted with what direction each number block goes ("8 r" = 8 goes right), and print to the terminal each and every move. If anyone could suggest how I could take an int and char at the same time from a line on a file, I would also be grateful.
CodePudding user response:
You can use fscanf()
, defined in stdio.h
, to read from a file:
int fscanf (FILE *stream, const char *format-string, argument-list)
stream
is a file you previously opened. fscanf()
returns the number of fields that it successfully converted and assigned. The return value does not include fields that the fscanf() function read but did not assign.
Example:
#include <stdio.h>
int main()
{
FILE* f = fopen("file.txt", "r");
int value;
char ch;
if (fscanf(f, "%d - %c", &value, &ch) != 2)
printf("Error");
printf("value: %d\nchar: %c\n", value, ch);
fclose(f);
return 0;
}
File file.txt content:
100 - A
Output:
value: 100
char: A
If your purpose is to parse a string, the simplest way to achieve this is to use strtok()
defined in string.h
header:
char *strtok(char *string1, const char *string2);