将一段文本加载到字符串向量中

时间:2013-04-27 20:04:05

标签: c++ vector

当我按原样运行此程序时,返回的文本没有任何空格。如何让它分别识别每个单词?

  int main()

{
    ifstream input1;
    input1.open("Base_text.txt");

    vector<string> base_file;
    vector<int> base_count;


    if (input1.fail())
    {
        cout<<"Input file 1 opening failed."<<endl;
        exit(1);
    }

    make_dictionary(input1, base_file, base_count);


}

void make_dictionary(istream& file, vector<string>& words, vector<int>& count)
{


    string word;
    int i=0;

    while (file>>word)
    {
        words.push_back(word);
        cout<<words[i];
        i++;
    }


    for (i=0; i<words.size(); i++)
    {
        if ((words[i+1]!=words[i]))
            {
                count.push_back(i);

            }
    }


}

当前输出:

Thisissomesimplebasetexttouseforcomparisonwithotherfiles.Youmayuseyourownifyousochoose;yourprogramshouldn'tactuallycare.Forgettinginterestingresults,longerpassagesoftextmaybeuseful.Intheory,afullnovelmightwork,althoughitwilllikelybesomewhatslow.

预期输出应在每个单词之间有空格。我需要能够在此之后按字母顺序对单词进行排序,因此我需要解决的不仅仅是输出。

2 个答案:

答案 0 :(得分:0)

更改此

cout<<words[i];

到这个

cout << words[i] << ' ';

请记住,您的程序正是您所说的。如果你不告诉它输出空格,它就不会。

答案 1 :(得分:0)

当您使用cout

输出单词时,需要添加包含空格的字符串
cout << " " << words[i];