gpt4 book ai didi

c++ - 硬件帮助 : get char instead of get line C++

转载 作者:行者123 更新时间:2023-11-30 04:32:15 25 4
gpt4 key购买 nike

我编写了下面的代码,成功地从文件中获取了随机行;但是,我需要能够修改其中一行,所以我需要能够逐个字符地获取该行。我怎样才能改变我的代码来做到这一点?

最佳答案

使用std::istream::get而不是 std::getline .只需一个字符一个字符地读取字符串,直到到达 \nEOFother errors .我还建议您阅读完整的 std::istream reference .

祝你作业顺利!

更新:

好吧,我不认为一个例子会造成伤害。如果我是你,我会这样做:

#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

static std::string
answer (const string & question)
{
std::string answer;
const string filename = "answerfile.txt";
ifstream file (filename.c_str ());

if (!file)
{
cerr << "Can't open '" << filename << "' file.\n";
exit (1);
}

for (int i = 0, r = rand () % 5; i <= r; ++i)
{
answer.clear ();
char c;

while (file.get (c).good () && c != '\n')
{
if (c == 'i') c = 'I'; // Replace character? :)
answer.append (1, c);
}
}

return answer;
}

int
main ()
{
srand (time (NULL));

string question;

cout << "Please enter a question: " << flush;
cin >> question;
cout << answer (question) << endl;
}

... 唯一的问题是我不知道为什么您需要一个字符一个字符地读取字符串才能修改它。您可以修改 std::string 对象,这更容易。假设您想将“我认为”替换为“如果”?你可能最好阅读更多关于 std::string并使用finderasereplace

更新 2:

您最新的代码所发生的事情很简单 - 您打开一个文件,然后逐个字符地获取其内容,直到到达换行符 (\n)。因此,无论哪种情况,您最终都会阅读第一行,然后您的 do-while 循环将终止。如果您查看我的示例,我会在 for 循环内执行 while 循环读取行直到 \n。所以这基本上就是你应该做的 - 重复你的 do-while 循环多次你想要/可以从该文件中获得的行数。例如,像这样的内容会读出两行:

for (int i = 1; i <= 2; ++i)
{
do
{

answerfile.get (answer);
cout << answer << " (from line " << i << ")\n";
}
while (answer != '\n');
}

关于c++ - 硬件帮助 : get char instead of get line C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7781410/

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