gpt4 book ai didi

c++ - 不能将 std::string 设置为等于另一个 std::string 的第零个索引

转载 作者:行者123 更新时间:2023-11-27 22:49:36 29 4
gpt4 key购买 nike

我正在尝试逐个字符地读取文本文件。我正在使用一个字符串来读取文件。我读取文件的代码如下:

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;
}

如您所见,在我的 for 循环中,我将字符串 tokenizer 设置为等于字符串 data_str 的第零个索引。但是编译的时候报错

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

我真的不知道我还能如何逐个字符地读取文件。我尝试将 tokenizer 设置为 char 类型。但是当我运行程序时,它说 counter 变量等于 0。所以很明显,将 tokenizer 变量设为 char 类型是行不通的。

如果需要,文本文件的内容如下:

 output: "Hello World

最佳答案

std::string data_str;

定义一个std::string

std::string tokenizer = data_str[i]

定义一个 std::string 并尝试用单个字符构造 stringstd::string 没有接受单个字符的构造函数。

鉴于您要将这个单个字符串与整个单词进行比较,这不是您想要做的。

data >> data_str;

读入以空格分隔的标记——实际上是一个单词加上任何标点符号。

所以

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

stripPunctuation 看起来像 void stripPunctuation(std::string & input) 并且会删除所有标点符号,但我只将这个 hack 作为一个简化示例。这种方法可行,但更好的解决方案类似于 changing the delimiter for cin (c++)。添加所有要删除的标点符号,让 >>> 为您完成这项工作。

然后你得到

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

大功告成。

关于c++ - 不能将 std::string 设置为等于另一个 std::string 的第零个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38799482/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com