读取一个句子,直到使用2-D char数组按下ENTER键

时间:2015-03-29 14:37:36

标签: c++ arrays string enter words

我需要逐字逐句地阅读句子,直到" ENTER"键是按下的。我使用do..while循环来读取单词,直到按下ENTER键。请建议我检查ENTER按键(或)其他方式读取类似输入的一些条件。

#include<iostream>
#include<string.h>
using namespace std;

int main(){

     char a[100][20]={'\0'};
     int i=0;

     do{
        cin>>a[i++];
     } while( \\ Enter key is not pressed );

     for(int j= 0 ; j < i ; j++)
        cout<< a[j] << " "; 
    return 0;
 }

5 个答案:

答案 0 :(得分:4)

声明

cin>>a[i++];

已经提示阻塞,直到按下 ENTER 键。因此,解决方案是一次读取一行(使用std::getline()),并在单独的步骤中解析单词。

当您的问题标记为时,您可以执行以下操作:

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

int main() {
    std::string sentence;
    std::cout << "Enter a sentence please: "; std::cout.flush();

    std::getline(std::cin,sentence);
    std::istringstream iss(sentence);

    std::vector<std::string> words;
    std::string word;
    while(iss >> word) {
        words.push_back(word);
    } 

    for(std::vector<std::string>::const_iterator it = words.begin();
        it != words.end();
        ++it) {
        std::cout << *it << ' ';
    }
    std::cout << std::endl; return 0;
}

请查看完整正常的demo


作为改进,当前标准为for()循环提供了更简单的语法:

    for(auto word : words) {
        std::cout << word << ' ';
    }

答案 1 :(得分:4)

while (cin.peek() != '\n') {
  cin >> a[i++];
}

答案 2 :(得分:1)

如何将此作为您的while语句使用

while( getchar() != '\n' );

您需要<stdio.h>头文件。

请参阅ideone link

答案 3 :(得分:1)

首先,我必须说πάνταῥεῖ的解决方案更好。 但是,如果你是初学者,对你来说可能会有很大帮助。 此外,我认为你想要二维数组,而不是矢量。

#include<iostream>
#include<string.h>
using namespace std;

int main(){

    /*
        All of this is simplified.
        For example there are no check if user entered word larger than 100 chars.
        And that's not all, but because of simplicity, and easy of understanding....
    */

     char a[100][20]={'\0'};
     char c;
     char buffer[2000];

    int i=0, j, k = 0;

    /*
        Read in advance all to way to ENTER, because on ENTER key all data is flushed to our application.
        Untill user hits ENTER other chars before it are buffered.
    */
    cin.getline(buffer, 2000, '\n');

     do {
         c = buffer[k++]; //read one char from our local buffer
         j = 0;

        //while we don't hit word delimiter (space), we fill current word at possition i
        // and of cource while we don't reach end of sentence.
         while(c != ' ' && c != '\0'){
             a[i][j++] = c;   //place current char to matrix
             c = buffer[k++]; //and get next one
         }

        i++;  //end of word, go to next one

        //if previous 'while' stopped because we reached end of sentence, then stop.
        if(c == '\0'){
             break;
        }


    }while(i < 20);


     for(j= 0 ; j < i ; j++)
        cout<< a[j] << " "; 

        cout << endl;

    return 0;
 }

答案 4 :(得分:0)

您可以尝试 cin.getline(buffer,1000);