读句子,直到ENTER键$ P $使用2-D字符数组pssed [英] Reading a sentence until ENTER key pressed using 2-D char array

查看:174
本文介绍了读句子,直到ENTER键$ P $使用2-D字符数组pssed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要阅读这个字的句子单词,直到ENTER键是pressed。我用do..while循环来读单词,直到ENTER键为pressed。请建议我检查ENTER键preSS(或)其他方式读取类似的输入一定的条件。

 #包括LT&;&iostream的GT;
#包括LT&;&string.h中GT;
使用命名空间std;诠释主(){     烧焦[100] [20] = {'\\ 0'};
     INT I = 0;     做{
        霉素>>一种[I ++];
     }而(\\\\回车键不pressed);     对于(INT J = 0; J< I; J ++)
        COUT<<一个研究[J]<< ;
    返回0;
 }


解决方案

语句

  CIN>>一种[我++];

块在已经提示,直到<大骨节病> ENTER 键pssed $ P $。因此,解决的办法是读一行一次(使用的std ::函数getline()),并解析它的话在单独的步骤。

你的问题被标记 C ++ ,你可以做到以下几点:

 的#include&LT;&iostream的GT;
#包括LT&;矢量&GT;
#包括LT&;串GT;
#包括LT&;&sstream GT;诠释主(){
    标准::字符串的句子;
    性病::法院LT&;&LT; 输入一个句子,请;的std :: cout.flush();    的std ::函数getline(给std :: cin,句);
    的std :: istringstream ISS(句);    的std ::矢量&lt;标准::字符串&GT;话;
    性病::串词;
    而(ISS&GT;&GT;字){
        words.push_back(字);
    }    对于(的std ::矢量&lt;标准::字符串&GT; ::为const_iterator吧= words.begin();
        !它= words.end();
        它++){
        性病::法院LT&;&LT; *它&LT;&LT; '';
    }
    性病::法院LT&;&LT;的std :: ENDL;返回0;
}

查看全部工作演示请。


作为改进现行标准提供了一个更简单的语法为()循环:

 为(自动字:字){
        性病::法院LT&;&LT;字LT;&LT; '';
    }

I need to read a sentence word by word until "ENTER" key is pressed. I used a do..while loop to read words until ENTER key is pressed. Please suggest me some conditions for checking ENTER key press (or) others ways for reading similar input.

#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;
 }

解决方案

The statement

cin>>a[i++];

blocks at the prompt already, until the ENTER key is pressed. Thus the solution is to read a single line at once (using std::getline()), and parse the words from it in a separate step.

As your question is tagged , you can do the following:

#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;
}

See the fully working demo please.


As an improvement the current standard provides an even simpler syntax for the for() loop:

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

这篇关于读句子,直到ENTER键$ P $使用2-D字符数组pssed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆