存储在char数组中的文件中的c++行

c++ line from file stored in char array

本文关键字:c++ 文件 数组 存储 char      更新时间:2023-10-16

我希望能够使用函数将整行读取到字符数组中。

示例输入文本为:

Schmidt, Helga
Alvarez, Ruben
Zowkowski, Aaron
Huang, Sun Lee
Einstein, Beverly

但是,我不知道如何将整行字符读入数组。我知道>>的分隔符是空白,但我不确定我是否将该分隔符改为"\n",如果它有效的话?

void buildList(char (*array)[25], ifstream& inputFile){
    string line;
    for (int i = 0; i < 5; i++)
        getline(inputFile, line);
        array[i] = line.c_str();     
}

目前,这只会在我的输入中读取姓氏或名字,而不是整行。我不知道如何才能改变这一点。谢谢

首先,您肯定要在这里使用std::string。一旦你这样做,您可以使用std::getline:

std::vector<std::string>
buildList( istream& input )
{
    std::vector<std::string> results;
    std::string line
    while ( std::getline( input, line ) ) {
        results.push_back( line );
    }
}

这将使代码更加简单和健壮。

如果你必须使用这样一个损坏的接口,那么有一个成员函数getline:

for ( int i = 0; i != 5; ++ i ) {
    input.getline( array[i], maxLength );
}

此外:函数应从不std::ifstream&作为参数(除非它要打开或关闭文件)。一应使用std::istream&

使用此-

void buildList(char (*array)[25], ifstream& inputFile){
    for (int i = 0; i < 5; i++)
        std::inputFile.getline(array[i],50);
}

getline的第二个参数是要写入字符数组的最大字符数。