1

我无法将字符串存储到数组中,当我输出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;
}
4

2 回答 2

3

您正在打印空字符串。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;
}

不要忘记处理文件名未传递或文件不存在的情况。

于 2013-07-19T09:14:49.540 回答
1

这可能有效

while(file >> s) {
            b[c]=s;
            cout<<b[c];
            c++;

        }
于 2013-07-19T09:19:26.173 回答