2016-06-13 122 views
5
#include <iostream> 
using namespace std; 
int main() 
{ 
    int n,t=0,k=0; 
    cin>>n; 
    char data[n][100]; 
    int num[n]; 
    for(int i=0;i<n;i++) 
{ 
    while(1) 
    { 
     cin>>data[i][t]; 
     cout<<data[i][t]<<endl; 
     if(data[i][t]=='\n') break; 
     k++; 
     if(k%2==1) t++; 
    } 
    cout<<i; 
    num[i]=(t-2)/2; 
    k=0; 
t=0; 
} 

    for(int i=0;i<n;i++) 
    { 
     while(1) 
     { 
      cout<<data[i][t]; 
      if(t==num[i]) break; 
      t++; 
     } 
     t=0; 
    } 
} 

這裏是我用C++編寫的代碼,它給出了用戶給出的每個單詞的起始一半的偶數字符,但是在按下輸入循環後給出輸入時應該中斷但使用「輸入」運營商>>跳過空白循環不打破C++中的break語句按回車鍵

while(1) 
{ 
    cin>>data[i][t]; 
    cout<<data[i][t]<<endl; 
    if(data[i][t]=='\n') break; 
    k++; 
    if(k%2==1) t++; 
} 
+0

什麼是真正的數據[I] [T]時,它應該打破? –

+1

你假設'cin'將默認包含換行符,並且從數據流中讀入數據。這是不正確的。 –

+3

*這是我用C++編寫的代碼* - 'cin >> n; char data [n] [100];' - 這是無效的C++。數組必須具有編譯時間大小。 – PaulMcKenzie

回答

9

默認格式輸入,並換行是一個空白字符。所以發生什麼事是>>運營商只是等待輸入一些非空白輸入。

說句輸入不要跳過空格,你必須使用std::noskipws機械手:

cin>>noskipws>>data[i][t]; 
0

已經有C來實現某些方面++什麼OP是試圖做。我開始避免使用可變長度數組,它們不在標準中,而是使用std::string s和std::vector s代替。

一種選擇是讀取輸入的整條生產線與std::getline,然後處理結果字符串保持均勻的字符只有上半年:

#include <iostream> 
#include <string> 
#include <vector> 

int main() { 
    using std::cin; 
    using std::cout; 
    using std::string; 

    cout << "How many lines?\n"; 
    int n; 
    cin >> n; 


    std::vector<string> half_words; 
    string line; 
    while (n > 0 && std::getline(cin, line)) { 
     if (line.empty())  // skip empty lines and trailing newlines 
      continue; 
     string word; 
     auto length = line.length()/2; 
     for (string::size_type i = 1; i < length; i += 2) { 
      word += line[i]; 
     } 
     half_words.push_back(word); 
     --n; 
    } 

    cout << "\nShrinked words:\n\n"; 
    for (const auto &s : half_words) { 
     cout << s << '\n'; 
    } 

    return 0; 
} 

另一個原因是,作爲約阿希姆Pileborg在他的回答一樣,通過格式的輸入功能與std::noskipws manipolator禁用領先空格跳躍,然後在一次讀一個字符:

// ... 
// disables skipping of whitespace and then consume the trailing newline 
char odd, even; 
cin >> std::noskipws >> odd; 

std::vector<string> half_words; 
while (n > 0) { 
    string word; 
    // read every character in a row till a newline, but store in a string 
    // only the even ones 
    while ( cin >> odd && odd != '\n' 
      && cin >> even && even != '\n') { 
     word += even; 
    } 
    // add the shrinked line to the vector of strings 
    auto half = word.length()/2; 
    half_words.emplace_back(word.begin(), word.begin() + half); 
    --n; 
} 
// ...