C++: Read from Text File and Separate into Variable

C++ read from a text file and seperate it into variables

You should use your outer loop to read a line, and your inner loop to split it using your delimiter.

Right now, your inner loop just removes the '.' at the end of each line.

Try something along the lines of:

while (std::getline(buildersList, line)) {
line.pop_back();//removing '.' at end of line
std::string token;
std::istringstream ss(line);

// then read each element by delimiter
int counter = 0;//number of elements you read
while (std::getline(ss, token, ':')) {//spilt into different records
switch (counter) {//put into appropriate value-field according to element-count
case 0:
name = token;
break;
case 1:
ability = stoi(token);
break;
case 2:
variability = stoi(token);
break;
default:
break;
}
counter++;//increasing counter
}
cout << name<<" "<<ability<<" "<<variability<<"\n";

}

Add error-checking as needed (e.g. for stoi)

C++: Read from text file and separate into variable

Something like this should work (I don't have a compiler handy, so you may need to tweak this a little):

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
ifstream inputFile("marks.txt");
string line;

while (getline(inputFile, line))
{
istringstream ss(line);

string name;
int var1, var2, var3;

ss >> name >> var1 >> var2 >> var3;
}
}

Edit: Just saw this again, I don’t know why I chose the get line approach earlier. Doesn’t the following (simpler solution) work?

#include <fstream>
using namespace std;

int main()
{
ifstream fin(“marks.txt”);

string name;
int var1;
int var2;
int var3;

while (fin >> name >> var1 >> var2 >> var3)
{
/* do something with name, var1 etc. */
cout << name << var1 << var2 << var3 << “\n”;
}
}

How to read data from a text file and store it in a variable in C language?

junk1 and junk2 should be arrays of char to be able to store strings.

But since it is junk you could simply not store it anywhere by using * in the fscanf conversion specifiers:

fscanf(file, "%*s %*s %lf\n", &Data[i]);

fscanf documentation:
https://en.cppreference.com/w/c/io/fscanf

Reading in a text file in C, separate lines into multiple variables

The file can be read fairly simply with fscanf() because everything except the first line identifier is a number. But you do need to check the validity of what is read from the file. I have just used exit(1) on error for illustration, it could be more sophisticated than that (for example an error message).

#include <stdio.h>
#include <stdlib.h>

#define MAX 100

struct processStruct {
int pNum;
int arTime;
int cpuBur;
int prio;
int waitTim;
};

struct processStruct structs[MAX];

int main(int argc, char** args)
{
FILE *fil;
char typeOf[4];
int numPro, i;
if ((fil = fopen("myfile.txt", "rt")) == NULL)
exit(1);
if(fscanf(fil, "%4s", typeOf) != 1)
exit(1);
if(fscanf(fil, "%d", &numPro) != 1)
exit(1);
if(numPro > MAX)
exit(1);
for(i=0; i<numPro; i++) {
if(fscanf(fil, "%d%d%d%d", &structs[i].pNum, &structs[i].arTime,
&structs[i].cpuBur, &structs[i].prio) != 4)
exit(1);
}
fclose(fil);

// test the result
printf("Type: %s\n", typeOf);
printf("Num: %d\n", numPro);
for(i=0; i<numPro; i++) {
printf("%d %d %d %d\n", structs[i].pNum, structs[i].arTime,
structs[i].cpuBur, structs[i].prio);
}
return 0;
}

Program output:

Type: SJF
Num: 4
1 0 6 1
2 0 8 1
3 0 7 1
4 0 3 1

How to assign variables from colon-separated text file c++

getline(ss, minimum, ':');

The second parameter to std::getline is always a std::string. minimum is not a std::string. It is an int, this is why this fails to compile. When calling a function in C++ all parameter types must be correct, or convertible (implicitly or by a user-specified conversion operator) to the parameter types that the function expects.

You need to extract this word into a std::string, too, then use the std::stoi library function to convert a std::string into an integer.

How do I load data from a txt file into variables in my C program?

I won't be writing the code, but can try to help with the algotihm, in general.

  1. Open the file. Help : fopen()
  2. Check for successful opening. Hint: Return value.
  3. Read a line from the file. Check for the success. Help : fgets() and Return value.
  4. Based on data pattern , tokenize the read line and store into the array. Help : strtok()
  5. Continue until token is NULL.

Note: At point 4, you need to convert some of the tokens to float type. Help: strtod()


EDIT:

Appriciate adding the code. Feedback for your code

  1. uncomment // exit(1);, you really should (note, not MUST, you can skip also) exit if the fopen() failed.

  2. fgets() reads one line at at time. So basically, you need three consecutive fgets() to populate one instance of the structure. first fgets() will give title, second one gain, third one offset.

  3. fgets() reads and stores the trailing \n. You may want to get rid of that.

  4. Use counter to track the structure array member index, too. Your array has only 8 elements here.

How to read variable separated by punctuations in a text file in C

If I understand your question, that you have a CSV with user info and the friends of that user, where the friends are encoded as a hyphen separated list of friend-IDs as the third field in the line, then you can use a combination of the re-entrant version of strtok (named strtok_r) to separate the comma separated fields, and than use calls to strtok within your outer loop to separate the hyphen separated values.

Note, strtok_r requires an additional "save pointer" as its third argument so that you can resume calls to that instance of strtok_r after having made intermediate calls to a difference instance of strtok or strtok_r for alternative separation purposes.

Given your line of:

"123456789,Jonh Brown,123456434-4325234-235234-42345234"

where 123456789 is the ID, Jonh Brown is the name, and 123456434-4325234-235234-42345234 is a list of friend IDs, you could parse the line and individual friends, just by keeping a field count and calling a separate instance of strtok within your tokinzation loop to separate friends on hyphens.

A short example would be:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FRIENDS 3

int main (void) {

char line[] = "123456789,Jonh Brown,123456434-4325234-235234-42345234",
*delims = ",\n", /* strtok_r delimiters for tokens */
*p = line, /* pointer to line */
*sp = p; /* save pointer for reentrant strtok_r */
int count = 0;

/* must use reentrant version of strtok to nest strtok use for friends */
p = strtok_r (line, delims, &sp); /* 1st call uses name of buffer */
count++;

while (p) { /* outputer tokenization loop */
printf ("token: '%s'\n", p);
if (count == FRIENDS) {
char *pf = calloc (strlen (p) + 1, 1), /* pointer to friends */
*delim2 = "-\n", /* delims for friends */
*f; /* pointer preserves pf */
if (!pf) {
perror ("malloc-pf");
exit (EXIT_FAILURE);
}
strcpy (pf, p); /* copy friends token to pf */
f = pf; /* set f, to pf, to preserve pf */
f = strtok (f, delim2); /* regular strtok OK for friends */
if (f)
printf ("friends:\n");
while (f) { /* friends tokenization loop */
printf (" %s\n", f);
f = strtok (NULL, delim2); /* subsequent calls use NULL */
}
free (pf); /* free allocated memory at preserved address */
count = 0; /* reset count */
}
p = strtok_r (NULL, delims, &sp); /* subsequent calls use NULL */
count++;
}

return 0;
}

(note: since strtok modifies the original string and advances the pointer it uses, you must make a copy of the friends token, and preserve a pointer to the starting address of the allocated token for friends (pf) so that it can be freed after you are done with separating friends)

(also note: if your system provides strdup, you can replace the two calloc (strlen (p) + 1, 1) and strcpy (pf, p); calls with a simple call to char *pf = strdup(p);. But note, since strdup allocates dynamically, you should still validate if (!pf) after the call)

Example Use/Output

$ ./bin/strtok_csv
token: '123456789'
token: 'Jonh Brown'
token: '123456434-4325234-235234-42345234'
friends:
123456434
4325234
235234
42345234

Look things over and let me know if you have further questions.

how to read a file and split each readed line into variables or array

That's strange...
You declare str (line 77):

char str[200];

Then you apply strtok to trash values on str (since you didn't initialize it)... (line 79)

char *  p    = strtok (str, "|");

Then you use p without properly initiating the variable(line 101):

    while (p) {

Maybe the problem is somewhere along there?

==============================================

EDIT:

First, it seems you are trying to save linea in str, so, you'll need to change str's declaration to this:

char str[LONG_MAX_LINEA];

Because you need to make sure that the destination string will have enough space.

Then you can't try to assign doing str[j] = linea; this is WRONG!
So that line should be changed to:

strcpy(str,linea);

Second, theres no point in doing strtok to trash value, so change p declaration to:

char *  p    = NULL;

Then, before the while, you write:

p = strtok (str, "|");

Does it work now?



Related Topics



Leave a reply



Submit