简体   繁体   English

您能否验证我的代码是否正确,以将字符串保存到struct中?

[英]Could you please verify if my code is correct for saving string to struct?

I am trying to file input information from a .txt file that has three inputs ie(Mike Jones 60) and inserting them into a structure C++ to use for my output to screen. 我正在尝试从具有三个输入(即Mike Mike 60)的.txt文件中归档输入信息,并将其插入到C ++结构中以用于输出到屏幕。

struct Person {
    string name;
    int age;
};
void addData()
{
    Person aPerson;
    char fileName[80];
    cout << "Please enter the file name: ";
    cin.getline(fileName, 80);
    //string fullName;
    ifstream fin(fileName);
    string tmp;
    stringstream ss;
    while (!fin.eof()) {
        getline(fin, aPerson.name);
        aPerson.name = tmp;
        getline(fin, tmp);
        ss << tmp;
        ss >> aPerson.age;
        ss.clear();
        getline(fin, tmp);
        ss.clear();
        cout << aPerson.name << aPerson.age << endl;
    }
}

This code will read data in this format: 此代码将以以下格式读取数据:

Joe Bloggs
42

Franziska von Karma
23

Jeff Jefferson
84

Is that what your input data looks like? 这就是您输入数据的样子吗?

If it's one line per person, and each person has exactly two words in their name, you can use the third parameter of getline to set a custom delimiter - instead of reading the whole line, it will read until it gets to a space. 如果每人一行,并且每个人的名字中恰好有两个单词,则可以使用getline第三个参数来设置自定义分隔符 -无需读取整行,它会一直读取直到到达空格为止。

Joe Bloggs 42
Jeff Jefferson 84
Amy Anderson 57

To process this data: 要处理此数据:

…
while (!fin.eof()) {
  string firstname;
  getline(fin, firstname, ' ');
  string surname;
  getline(fin, surname, ' ');
  aPerson.name = firstname + " " + surname;
  string age;
  getline(fin, age);
  ss << age;
  ss >> aPerson.age;
  cout << aPerson.name << aPerson.age << endl;
  ss.clear();
}

If you can get the data in Comma-Separated Data format, or tab-separated, or anything-that's-not-a-space-separated, you can use that delimiter and extract the data in two steps not three. 如果您可以逗号分隔数据格式,制表符分隔或任何不是空格分隔的格式获取数据,则可以使用该定界符并分两步而不是三步提取数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM