2016-11-20 146 views
-1

所以我想從文本文件中提取一行,並提取每行中的第一個字並保存在字符數組「op」中。我在處理第一個單詞之前的空格時遇到了麻煩。文中的第一行是「真棒醬油」,第二行是「是」,第三行是「酷」,第四行是「是的好」。在單詞yeah之前處理空格有困難。從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

做什麼? –

+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

ü應使用k開始串提取要連接所有的第一句話該文件以一個字符數組運算在

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