来自 C++ 中 next/new 行的 ifstream

ifstream from next/new line in c++

我将一组数据存储在一个文件中,这些数据基本上都是名称。我的任务是获取每个名字的所有首字母。这是文件:

Jack fisher
goldi jones
Kane Williamson
Steaven Smith

我只想从每行中取出第一个词(例如 jack、goldi、kane、Steaven) 我为它写了下面的代码,只是为了取出 2 个名字。这是:

    string first,last;
    ifstream Name_file("names.txt");
    Name_file>>first;
    Name_file>>endl;
    Name_file>>last;
    cout<<first<<" "<<last;

报错。如果我删除 endl,它会使用第一个全名(Jack、fisher),而我希望它应该使用(jack、goldi)。怎么做 ?任何的想法?在此先感谢您的帮助。

Name_file>>endl;总是错的。

即便如此,你也不能像那样使用 >>,它会在 space 处停止,这就是为什么当你删除 endl 时你会看到 firstlast 只包含第一行。

改为使用 std::getline 遍历文件并获取全名,然后在第一个 space 处拆分行以获取名字:

ifstream Name_file("names.txt");

std::string line;
while (std::getline(Name_file, line))
{
  std::string firstName = line.substr(0, line.find(' '));
  //do stuff with firstName..
}

希望这能解决您的问题。

ifstream Name_file;
string line;
Name_file.open("names.txt");
if(Name_file.fail()){ cerr<<"Error opening file names.txt !!"<<endl;return;}

vector<string> v; // array to store file names;

while(Name_file >> line){
    string word;
    getline(Name_file, word);
    v.push_back(line);
}

// printing the first names
for(int i = 0; i < v.size();i++){
    cout<<v[i]<<endl;
}

虽然我不介意“Hatted Rooster”的实现,但我认为当输入突然包含很长的一行时,它的效率可能会降低一些。

我会使用 ignore() 删除该行的其余部分:

int main()
{
    std::ifstream nameFile("names.txt");
    std::string firstName;

    while (nameFile >> firstName)
    {
        // You got a first name.
        // Now dump the remaing part of the line.
        nameFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}