如何在c ++中用字符串创建变量

时间:2015-02-03 12:21:46

标签: c++

这是我的代码,输出是与成绩相关的数字。我希望能够使字符串的每一行成为一个变量,如int grade1等,这样我就可以显示某些变量,而不是整个字符串,例如cout<<等级1<<等级2<< ENDL;

using namespace std;
int main()
{

    string line;
    ifstream myfile("Data.csv"); //opening the CVS file
    if (myfile.is_open())
    {
        while (getline(myfile, line)) //used to read each line of the file
        {

            string str(line); //making the file a string

            char chars[] = ",abcdefghijklmnopqrstuvwxyzN;:/"; //Characters to be removed

            for (unsigned int i = 0; i < strlen(chars); ++i)
            {
                str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end());
            }

            str.replace(0, 9, " ");

            cout << str << endl;
        }

        myfile.close(); //closes the file

    }
    else
        cout << "pathway to file can't be found" << '\n'; //error message to display if file location cant be found. 

    cin.get();

    return 0;
}

1 个答案:

答案 0 :(得分:1)

问题,特别是代码很难理解,但我知道你想为文件的每一行创建字符串变量。

一种简单的方法是逐行循环遍历文件,将该行存储到字符串变量中,然后将该变量推送到矢量。

std::string line;
std::vector<std::string> lines;

while (getline(myfile, line))
{
    lines.push_back(line);
}