gpt4 book ai didi

c++ - 我如何使用文本文件接收多个单词

转载 作者:太空宇宙 更新时间:2023-11-04 13:06:58 25 4
gpt4 key购买 nike

这是我的代码:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
//ifstream for input from files to program
//ofstream for output to file
string str;

ofstream PI_file("test.txt");
PI_file <<"Has this reached the file";
PI_file.close();

ifstream TO_file("test.txt");
TO_file >> str;

cout << str;
}

当我输出 str 时,它只打印“Has”,所以只有文件 TO_file 的第一个单词到达了 str。为什么是这样?另外,我该如何修复它以便接收整个文件?

此外,我的另一个问题是,如果我想使用 for 循环遍历字符串中的每个字母或单词,我可以使用:

for (int i=0; i<string.length(); i++)

但是如果我想遍历文件直到到达文件中的最后一个单词或字母,我该怎么做呢?我可以使用“test.txt”.length() 或者 TO_file.length() 吗?或者还有其他方法吗?

最佳答案

只是想纠正你,你发送到 test.txt 的整行已经成功到达那里。我刚刚测试了你的代码。虽然它只输出 Has,但整行 Has this reached the file 实际上在 test.txt 中。

您的代码中的问题在于您如何读取文本文件。当您执行以下行时,

    TO_file >> str;

你忘记了 str 是一个字符串类型的变量。如果您曾经尝试接受字符串变量的输入,编译器将只接受空格字符之前存在的内容,就像您的行中的单词 Has 之后一样。例如,

     string s;
cin >> s;

如果您输入“Hello there!”,编译器只会将第一个单词(即 Hello)存储在变量 s 中。同样,在您的函数中,只有行的第一个单词会传输到 str 变量。

您将不得不重写代码以读取 test.txt。我将提供来自 cplusplus.com 的示例模板下面:

      string line; // You store the string sentence in this variable
ifstream myfile ("example.txt"); // You open the file in read mode
if (myfile.is_open()) // If the file is successfully accessed and opened, then:
{
while (getline (myfile,line)) // Get every line from the file until you reach end of file
{
cout << line << '\n'; // Here you do whatever you want to do with the line from the file
}
myfile.close(); // Close the file at the end
}

else cout << "Unable to open file"; // If the file cannot open, print error message

你的代码错误在 while 循环的条件下被修复:

        getline (myfile,line)

不是简单地获取第一个单词,而是可以获取文件中的整行(只是一行,而不是整个文本文件)并输出。从这里开始应该非常简单。祝你好运!

关于c++ - 我如何使用文本文件接收多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41771641/

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