我无法将字符串存储到数组中,当我输出 b[c]
时什么也没有出现,我如何将它存储到数组中?
int main(int argc, char *argv[])
{
string b[80000];
int c=0;
string s;
ifstream file(argv[1]);
while(file >> s) {
b[c]=s;
c++;
cout<<b[c];
}
system("pause");
return 0;
}
最佳答案
您正在打印空字符串。随便动一下cout << b[c];
之前c++;
我建议使用 std::vector
,它将避免不必要的临时变量和魔法常量:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
int main(int argc, const char* argv[])
{
std::ifstream fin(argv[1]);
std::vector<std::string> v
{
std::istream_iterator<std::string>(fin),
std::istream_iterator<std::string>()
};
for(const auto& elem: v)
std::cout << elem << std::endl;
return 0;
}
不要忘记处理未传递文件名或文件不存在的情况。
关于c++ - 我无法将字符串存储到数组中,然后我想将其用于比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17742285/