Mr.goosberry Mr.goosberry - 3 months ago 8
C++ Question

cannot set a std::string equal to the zeroth index of another std::string

I'm attempting to read a text file character by character. I'm using a string to read the file. My code for reading the file is below:

int main()
{
std::ifstream data;
data.open("C:\\Users\\Christian Dean\\Documents\\CodeLiteWorkspace\\CplusplusPractice\\src\\test_file.qz");
std::string data_str;
int counter = 0;
data >> data_str;
for(int i = 0; i < data_str.length(); i++)
{
std::string tokenizer = data_str[i];
if (tokenizer == "output")
{
counter++;
}
}
std::cout << counter << std::endl;
data.close();
return 0;
}


as you can see, in my for loop I'm setting the string
tokenizer
equal to the zeroth index of the string
data_str
. However when compiling, it show the error


`main.cpp:27:37: error: invalid conversion from 'char' to ''const char*' [-fpermissive].


I really don't know how else I can read the file character by character. I tried setting
tokenizer
as type
char
. But when I run the program it says the
counter
variable equals
0
. So obviously making the
tokenizer
variable a type
char
did not work.

The content of the text file is below if it is needed:

output: "Hello World

Answer
std::string data_str;

defines a std::string.

std::string tokenizer = data_str[i]

defines a std::string and attempts to construct the string with a single character. std::string has no constructor that accepts a single character.

Seeing as you're going to compare this single character string against a whole word, this isn't what you want to do anyway.

data >> data_str;

reads in whitespace delimited token--effectively one word plus any punctuation.

so

while (data >> data_str)
{
    stripPunctuation(data_str);
    if (data_str == "output")
    {
        counter++;
    }
}

stripPunctuation would look like void stripPunctuation(std::string & input) and would remove all punctuation, but I only included that hack as a simplified example. This approach would work, but a better solution is something like changing the delimiter for cin (c++) to add all the punctuation you want to strip and let >> do the job for you.

Then you get

// configure stream to treat punctuation as whitespace here
while (data >> data_str)
{
    if (data_str == "output")
    {
        counter++;
    }
}

and you're done.