2013-10-12 41 views
1

我有了字符串,例如讀取一行同時C++

文件你好,我的名字是喬

你怎麼樣?

好嗎?

我試圖輸出該文件,但我的程序輸出爲「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(); 

return 0;

+1

你可能想看看'std :: getline'。 – juanchopanza

+0

使用'getline'方法 – Kunal

回答

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; 
+0

+1,但也許使用迭代器遍歷向量。 – 2013-10-12 18:09:37

+0

我得到這行代碼「line.push_back(word);」的錯誤它說「class std :: vector >'沒有名爲'pushback'的成員 make:」對此有何想法? – Mdjon26

+0

@ Mdjon26'pushback'!='push_back' – WhozCraig

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; 
}