2016-11-20 3 views
-1

テキストファイルからgetlineし、各行の最初の単語を抽出し、char配列 "op"に保存します。私は最初の単語の前に来るスペースに対処するのに苦労しています。テキストの最初の行は「素晴らしいソース」、2番目は「はい」、3番目は「クール」、4番目は「そうです"それは言葉の前にスペースを扱うのに苦労している。文字列を使用しないでgetlineから文字配列を取り出す

infile.open( "vec.txt");

//define line pointer 

char* line=new char[100]; 
char other[100]; 
char op[100]; 
int numofLines = 0; 
int k = 0; 
bool wordStart = false; 

//get line 
while (infile.getline(other,100)) 
{ 
    int numofChar = k; 
    int numofOpChar = 0; 
    int r = 0; 
    int p = 0; 

    while (other[k] == ' ') 
    { 
     while (other[k] != ' ') 
     { 
      wordStart = true; 
     } 
     k++; 
     cout << k << endl; 
    } 

    if (wordStart = true) 
    { 
     do 
     { 
      op[numofOpChar] = other[numofChar]; 
      numofChar++; 
      numofOpChar++; 

     } 
     while (other[numofChar] != ' '); 

     if (op[numofChar] != ' ') 
     { 
      cout << op << endl; 
     } 

    } 

}

+0

を開始するためにKを使用する必要があり、あなたは一つの文字列OPにファイル内のすべての最初の単語を連結しますか? –

+0

いいえ、私はオペコード配列に最初の単語が含まれるようにするたびに、各インスタンスで。 – ruchithelamp

+0

あなたはデバッガでコードをステップ実行しますか?どこが間違っていますか? – pm100

答えて

0

私は何が必要正しくあなたを理解している場合は以下のとおりです。わかりやすくするためにファイルの代わりにstd::stringstreamを使用しました。

#include <iostream> 
#include <sstream> 
#include <cstring> 
#include <limits> 

int main() 
{ 
    const size_t N = 100; 
    const char text[] = "awesome sauce\n" "yes\n" "cool\n" " yeah ok"; 
    char line[N]; 
    char op[N]; 
    size_t pos = 0; 

    std::istringstream is(text); 

    while (is >> op) 
    { 
     is.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
     std::cout << op << std::endl; 
    }  

    return 0; 
} 

プログラムの出力は

awesome 
yes 
cool 
yeah 
0

であるuが列抽出

numofchar = k; 
if (wordStart = true) 
{ 
    do 
    { 
     op[numofOpChar] = other[numofChar]; 
関連する問題