1

次のような文字列を含むファイルがあります

こんにちは私の名前はジョーです

元気にしてる?

いいですか?

そのファイルをそのまま出力しようとしているのですが、私のプログラムは「HellomynameisJoeHowAreyouDoing?Goodyou?」と出力しています。スペースと改行に問題があります。

int main (int argc, char* argv[])

{
index_table table1;

string word;
ifstream fileo;

    fileo.open(argv[1]); //where this is the name of the file that is opened

    vector<string> line;

    while (fileo >> word){
        line.push_back(word);
    }
    cout << word_table << endl;
    for (int i=0; i < line.size(); i++)
    {
        if (find(line.begin(), line.end(), "\n") !=line.end()) 
            cout << "ERRROR\n"; //My attempt at getting rid of new lines. Not working though.
        cout << line[i];
    }
    fileo.close();

0 を返します。

4

2 に答える 2

7

使用するだけです:std::getline

while (std::getline(fileo, word))
{
        line.push_back(word);
}

その後、

for (int i=0; i < line.size(); i++)
{
  std::cout<<line[i]<<std::endl;
}

または単に:-

std::copy(line.begin(), line.end(),
           std::ostream_iterator<std::string>(std::cout, "\n") );

//With C++11
for(const auto &l:line)
  std::cout<<l<<std::endl;
于 2013-10-12T18:07:06.980 に答える
0

別の解決策 (カスタム ループなし):

#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

struct line_reader : std::ctype<char>
{
    line_reader() : std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask> rc(table_size, std::ctype_base::mask());
        rc['\n'] = std::ctype_base::space;
        rc[' '] = std::ctype_base::alpha;
        return &rc[0];
    }
};

int main()
{
    std::ifstream fin("input.txt");
    std::vector<std::string> lines;
    fin.imbue(std::locale(std::locale(), new line_reader())); // note that locale will try to delete this in the VS implementation
    std::copy(std::istream_iterator<std::string>(fin), std::istream_iterator<std::string>(), std::back_inserter(lines));
    // file contents now read into lines
    fin.close();
    // display in console
    std::copy(lines.begin(), lines.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
    return 0;   
}
于 2013-10-12T21:32:12.843 に答える