编辑 - 没有空行。 编辑 2 - 我的错,看来我一直都错了。某处有一个空行,尽管 csv 文件另有说明。它现在正在工作。 好的,这是整个(简短的)程序:
#include <iostream>
#include <cctype>
#include <string>
#include <fstream>
using namespace std;
int main(){
char a;
string stringmanip;
fstream myfile("readthisfile.csv");
if (myfile.is_open()){
while ( myfile.good() ){
getline(myfile,stringmanip);
a=stringmanip[0];
}
myfile.close();
}
else cout<< "Unable to open file";
return 0;
}
这对我来说毫无意义。我可以复制 stringmanip,我可以 cout stringmanip,我可以将 .substr 与 stringmanip 一起使用。如果我定义一个常规字符串,我可以很好地使用 [] 操作。我也尝试过 .at,但这只会导致另一个错误。 (超出范围)。
如有任何帮助,我们将不胜感激。抱歉,我是一个初学者,我相信你能看出来。
谢谢, 本
最佳答案
如果 readthisfile.csv 在文件末尾(或文件中的任何位置)有一个空行,那么您将得到一个空字符串。您不能取消引用空字符串的第 0 个字符。 string::operator[]
只接受从 0
到 string::length() - 1
的索引。如果您有一个空字符串,对 string::operator[]
的任何调用都将导致未定义的行为。
关于c++ - 使用 C++,为什么我会收到错误消息 "string subscript out of range"而我知道它不是?或者至少看起来是这样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10097725/