【问题标题】:Substring and Erase子串和擦除
【发布时间】:2017-07-17 05:16:50
【问题描述】:

我正在尝试创建一个 while 循环,只要从文件中获取的字符串不为空,该循环就会运行。我需要用空格分隔字符串并保存信息以供将来使用,因此我将子字符串放入数组中,然后将其从实际数组中删除。但是,当我运行程序时,我不断收到一条错误消息,或者只打印空白。 I added a picture of the file I'm using and of the error message I'm getting

fstream myfile;
string line;
string info[10000];
int i=0, pos;

myfile.open("bfine_project1_input.txt");
//Check
if (myfile.fail()){
    cerr << "Error opening file" << endl;
    exit(1);
}

if (myfile.is_open()){
    while (getline (myfile,line)){
        while(line.size() !=0){
            pos = line.find(" ");
            info[i]= line.substr(0,pos);
            i++;
            cout << info[i] << endl;
            //line.erase(0, pos);
        }
    }
}

【问题讨论】:

  • 信息是vector吗?如果是这样,它的大小是否合适?
  • 信息是一个数组
  • 信息如何声明?我如何声明?我被分配到哪里去了?你得到什么错误信息?为什么 SO 需要minimal reproducible example
  • 请不要张贴文字图片。如果您有错误消息,请将其文本作为文本发布。
  • 您不需要从字符串line 中删除任何内容。只需继续复制子字符串并更新位置即可。

标签: c++ file io substring erase


【解决方案1】:

我可以看到两个问题。

1st - 在打印之前增加“i”(将值存储在 info[0] 中并打印 info[1])

第二次 - 擦除你正在使用的方式不会擦除空格“”,因此 find(" ") 将从第二次向前返回位置 0。

一些调整可以解决这个问题。请看下面的代码:

重要提示:您的代码编写方式需要在行尾有一个空格!

string line;
string info[10000];
int i=0, pos;

line = "1325356 134 14351 5153613 1551 ";
while(line.size() !=0){
    pos = line.find(" ");
    info[i]= line.substr(0, pos);
    cout << i << " " << info[i] << endl;
    line.erase(0,pos+1); //ERASE " " too!
    i++;//increment i only after everything is done!
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 2019-09-30
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多