2016-03-25 7 views
-1

ロングストーリーショートプログラムを正しく動作させるために独自の新しい行を作成せずに、私のベクトルを1行として扱う必要があります。 iはベクトルに読み込まれたテキストファイルは私はテキストファイルから私のベクトルを提出し、それは1行としてcoutをしない。これどうやってするの?

laptop#a small computer that fits on your lap# 
helmet#protective gear for your head# 
couch#what I am sitting on# 
cigarette#smoke these for nicotine# 
binary#ones and zeros# 
motorcycle#two wheeled motorized bike# 
oj#orange juice# 
test#this is a test# 

ループ用いてベクターを充填した:

if(myFile.is_open()) 
{ 
    while(getline(myFile, line, '#')) 
    { 
     wordVec.push_back(line); 
    } 
    cout << "words added.\n"; 
} 

をし、この使用して印刷:

for(int i = 0; i < wordVec.size(); i++) 
{ 
    cout << wordVec[i]; 
} 

を、それのような出力:

laptopa small computer that fits on your lap 
helmetprotective gear for your head 
couchwhat I am sitting on 
cigarettesmoke these for nicotine 
binaryones and zeros 
motorcycletwo wheeled motorized bike 
ojorange juice 
testthis is a test 

私のプログラムは私がmanu仲間は単語を入力してデータ構造に追加しますが、テキストファイルで埋め込まれたベクトルから追加した場合、プログラムの半分は機能しません。誰もが問題のより良い説明を求める前に、私が知る必要があるのはベクトルをどのように埋めて1行として出力するかだけです。

答えて

2

コードgetline(myFile, line, '#')は、すべての改行を含むファイルの最後まで、または次の '#'をlineに読み込みます。だから、あなたは...あなたはまたlineが連続した値を取る...

...など
"laptop#a small computer that fits on your lap#\nhelmet#protective gear for your head#" 

を考えることができた... ...

laptop#a small computer that fits on your lap# 
helmet#protective gear for your head# 

をテキストファイルの内容を読んで

"laptop" 
"a small computer that fits on your lap" 
"\nhelmet" 
...etc.... 

"\nhelmet"に改行があることに注意してください。

バリーはコメントで示唆するような...

while ((myFile >> std::skipws) and getline(myFile, line, '#')) 
    ... 

...か...

if (not line.empty() and line[0] == '\n') 
    line.erase(0, 1); 

...または(などこれを回避または修正する多くの方法がありますが、ここでは)...

while (getline(myFile, line)) 
{ 
    std::istringstream iss(line); 
    std::string field; 
    while (getline(iss, field, '#')) 
     ... 
} 
+1

または読み取りライン・バイ・ラインが、その後、各ライン内 –

+1

@BarryTheHatchetトークン化:真 - あなたが診断メッセージの行番号をカウントすることができますので、とにかく、しばしば望ましいが.... –

+0

@BarryTheHatchetので、どのように私はラップトップの#aを回すことができますあなたのラップにフィットする小さなコンピュータstring1 =ラップトップとstring2 =ラップに収まる小さなコンピュータ。投稿した2つの提案は機能しませんでした。 – ThePeskyWabbit

1
while(getline(myFile, line, '#')) 

、あなたはを語りましたは改行文字の代わりに '#'文字を使用し、'\n'を区切り文字として使用します。

したがって、std::getlineは、'\n'について特別なことはもう考えられなくなります。それはstd::getline()が次の#を探して読み続けるという別の文字です。

したがって、改行文字を個々の文字列に読み込み、出力した文字列の一部としてstd::coutに出力します。

関連する問題