2016-06-13 126 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; 
} 
// ...