-
Reading string
Hello, I am trying to read a line of characters separted by commas from a file. I need to be able to use the string groups before each comma later in my program. I have been using the "find()" function and the
"substr()" function, but I am having difficulting. Help in any form will be greatly appreciated. Thank you in advance.
-
read in a line using getline, then use find, im just goint to put each word into a vector:
Code:
vector<string> vec;
string strLine;
getline(inFile,strLine);
int cpos = strLine.find(",");
while(cpos)
{ vec.push_back(strLine.substr(0,cpos);
strLine = strLine.substr(cpos+1,strLine.length()-cpos);
cpos = strLine.find(",");
}
that should work, havent tested it though.
-
Vector?
I am pretty new to the programming game, so I am unfamiliar with vectors. Can you please give me an alternative? Once again, thank you in advance and your help is greatly adored.
-
just make an array of strings,
Code:
string myStrings[100];
getline(inFile,strLine);
int cpos = strLine.find(",");
int index = 0;
while(cpos && index < 100) // 100 b/c thats the size of myStrings
{ myStrings[index] = strLine.substr(0,cpos);
index++;
strLine = strLine.substr(cpos+1,strLine.length()-cpos);
cpos = strLine.find(",");
}
-
Just a note. Don't use that "while (cpos)" stuff because string::find() returns string::npos (which is -1) if the search data isn't located. you'll be stuck in an infinite loop. check if cpos == -1. it makes sense because if find() returned 0 when it didn't find a match, it would be telling you that it was located at the first position of the string.
-
like i said i thought of that right off the top of my head fast.
-
strtok
You can also sequentially truncate string by delimiters - in your case the ",":
http://www.cplusplus.com/ref/cstring/strtok.html
-
Array of Strings
I have tried all of your suggestions and I understand how the code came about, but I am coming up with this one huge error. It prints out
"no suitable conversion function 'std::basic_string<char, std::char_traits<char>, std::allocator<char>> ' to
'char' exists myStrings[index] = strLine.substr( 0, cpos);"
where int cpos = strLine.find(":");
Can you tell me what that means?
Thank you for all of your previous help :) !
-
how did you declare your array? did you declare it as a char array?, if so it should be a string array, because that code compiles for me exactly how it is.
Code:
string myArray[100];
-
Array of Strings
Yes, I declared the array string, but i didn't not include the amount of elements in the array for it is unknown and subject to change.
-
string ** myArray = new string*;
*myArray = new string[max_elements];
Or if you want to have more control over constructors and size, just do:
string ** myArray = new string*;
while(!done) {
*(myArray++) = new string("blah");
}