将文件中的行追加到字符数组中


char wordList[200];
ifstream wordListFile ("wordlist.txt");

for(std::string line; getline(wordListFile, line); ) {
wordListFile >> wordList;
}

此代码当前返回wordListFile (wordlist.txt)末尾的行,

是否有办法将这些行附加到wordList上?

因为当我使用append()函数时,它返回一个错误。

在循环中

for(std::string line; getline(wordListFile, line); ) {
wordListFile >> wordList;

您正在读取getline(wordListFile, line);的一行输入,但没有对该行进行任何操作。相反,您正在阅读带有wordListFile >> wordList;的下一行的第一个单词。这没有意义。

如果您想将行内容附加到wordList,那么您可以将wordList初始化为空字符串,然后使用std::strcat:

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
int main()
{
char wordList[200] = "";
std::ifstream wordListFile( "wordlist.txt" );
for ( std::string line; std::getline(wordListFile, line); ) {
std::strcat( wordList, line.c_str() );
}
std::cout << wordList << 'n';
}

对于输入

This is line 1.
This is line 2.

这个程序有以下输出:

This is line 1.This is line 2.

可以看到,这些行被正确地追加了。

然而,这段代码是危险的,因为如果文件对于数组wordList来说太大,那么就会出现缓冲区溢出。

更安全、更有效的方法是使wordList类型为std::string,而不是c风格的字符串:

#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string wordList;
std::ifstream wordListFile( "wordlist.txt" );
for ( std::string line; std::getline(wordListFile, line); ) {
wordList += line;
}
std::cout << wordList << 'n';
}

这个程序有相同的输出:

This is line 1.This is line 2.

你只能在std::string上使用append,但你的wordList是一个字符数组。

string也不是list。可能(但我猜)你想要这样的代码

std::vector<std::string> wordList;
for (std::string word; wordListFile >> word; ) {
wordList.push_back(word);
}

这里wordList是一个字符串向量,push_back把你读到的每个单词加到这个向量上。

如果你真的想在列表中添加行而不是单词,那么只需使用getline而不是>>

std::vector<std::string> lineList;
for (std::string line; getline(wordListFile, line); ) {
lineList.push_back(line);
}

因为当我使用append()函数时,它返回一个错误。

std::string::append (2)works well.

std::string wordList;
ifstream wordListFile ("wordlist.txt");
for(std::string line; getline(wordListFile, line); ) {
wordList.append(line);
}
std::string wordList;
std::ifstream wordListFile ;
wordListFile.open("wordlist.txt");
std::getline(wordListFile , wordList);
wordListFile.close();

试试这段代码。你可以从文件中得到整个字符串。我希望这能帮到你。

最新更新