0
int line = 0;
string teststring = " ";
string stringarray[100];

while (codeFile.good())
{
    getline(codeFile, teststring, ' ');

    if(teststring!="" && teststring[0]!='\n' && teststring[0] != 9 && teststring[0] != 10 && teststring[0] != 32 && teststring[0]!=' '
            && teststring!=" " && teststring!="  ")
    {
        stringarray[line]=teststring;        // still stores whitespace :(
        cout << stringarray[line] << endl;
        line++;
    }
}

Hello, I am going through a text file and trying to store each string inside an element of an array but, am having problems with elements storing completely white space.

duppydodah
  • 1
  • 1
  • 3
  • Of topic: Consider `vector stringarray` instead of `string stringarray[100];` – 4386427 Apr 10 '17 at 04:52
  • 1
    Maybe you'll find this useful: http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c – 4386427 Apr 10 '17 at 04:54
  • `while (codeFile.good())` is a variant of `while (!codeFile.bad())` and both fail for the same reason: They test if data is good before reading data, leaving the status of the just-read data unknown. This looks like test, read, use, potentially using bad data. What you want to do is read, test, use, that way you know what you read can be safely used. – user4581301 Apr 10 '17 at 05:24
  • [`std::isspace`](http://en.cppreference.com/w/cpp/string/byte/isspace) can be used for whitespace detection – pergy Apr 10 '17 at 06:15

2 Answers2

0

I have just solve a similar problem, how about this code:

while (codeFile.good())
{
    getline(codeFile, teststring);
    for(size_t idx = 0; idx < teststring.size(); i++) {
        size_t start = idx;
        while (teststring[i] != ' ') {
            idx++;
        }
        stringarray[line] = teststring.substr(start, idx - start);
        cout << stringarray[line] << endl;
        line++;
    }
}
Jiahao Cai
  • 1,194
  • 1
  • 10
  • 22
0

Ignoring all the white spaces is exactly what operator>> does.

Your snippet can be rewritten as:

// ...
std::string word;
std::vector<std::string> words;

while ( codeFile >> word )
{
    if ( word.empty() ) continue;
    std::cout << word << '\n';
    words.push_back(std::move(word));
}
Bob__
  • 9,461
  • 3
  • 22
  • 31