Is there a better way to parse a line of text?

I have a text file with lines of text in which there is a line, another line, followed by up to 4 integers, for example:

clear "clear water.png" 5 7 wet "wet water.png" 9 5 33 17 soft "soft rain falling.png" 

The only thing I see is:

read until a place is found

set the string to wet

read up to double quotes

read up to second double quotation mark

set the second line for wet water. png

until the end of the line

read to space

put a line through a stream of lines

hit the resulting integer into vector int

Is there a better way to do this?

thanks

+4
source share
4 answers

This is the task for which scanf and company really shine.

 char first_string[33], second_string[129]; sscanf(input_string, "%32s%*[^\"]%*c%128[^\"]%*c %d %d %d %d", first_string, second_string, &first_int, &second_int, &third_int, &fourth_int); 

You probably want to do this in the if so that you can check the return value to tell you how many of these converted fields (for example, you know how many integers you read at the end).

Edit: maybe some explanation would be helpful. Let it dissipate that:

% 32s reads the line in the first space (or 32 characters, whichever comes first).
% * [^ \ "] ignores input before the first " .
% * c ignores another input byte (quote itself)
% 128 [^ \ "] reads the string in the quote (ie, until the next quote character).
% * c Ignores the final quote% d Reads int (which we did four times).

The space in front of every %d really unnecessary - it skips spaces, but without a space, %d skips leading spaces anyway. I have included them solely to make it more readable.

+5
source

Awful, without error checking, but does not depend on any non-standard libraries:

 string s; while(getline(fin, s)) { string word, quoted_string; vector<int> vec; istringstream line(s); line >> word; line.ignore(numeric_limits<streamsize>::max(), '"'); getline(line, quoted_string, '"'); int n; while(line >> n) vec.push_back(n); // do something with word, quoted_string and vec... } 
+1
source

Depending on the limitations of the input lines, you can try splitting into double-quote and then into space .

0
source

Yes

Use getline to read one line at a time. Parse strings using the regex library .

0
source

Source: https://habr.com/ru/post/1384419/


All Articles