通过按ENTER中的C 中的断点语句

break statement in c++ by pressing enter

本文关键字:断点 语句 中的 ENTER      更新时间:2023-10-16
#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 编写的代码,该代码从用户给出的每个单词的起点中均匀编号的字符,但是当按下输入输入时,请输入循环,但循环不会破坏

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

默认情况下使用"输入"操作员>>跳过白空间,而newline是一个白空间字符。因此,发生的事情是>>操作员只需等待输入一些非白色空间输入。

要告诉输入不要跳过白空间,您必须使用std::noskipws操纵器:

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

有一些方法可以在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:nn";
    for ( const auto &s : half_words ) {
        cout << s << 'n';
    }
    return 0;
}

另一种是,就像Joachim Pileborg在答案中所做的那样,通过使用std::noskipws Manipolator的格式输入功能禁用领先的空格,然后一次阅读一个char:

// ...
// 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;
}
//  ...