繁体   English   中英

在 C++ 中获取多行输入

[英]Getting multiple lines of input in C++

第一行包含一个整数 n (1 ≤ n ≤ 100)。 以下 n 行中的每一行都包含一个单词。 所有单词均由小写拉丁字母组成,长度为 1 到 100 个字符。 (来源: http : //codeforces.com/problemset/problem/71/A

给定n,您将如何从用户那里获得输入? 我尝试使用 while 循环,但它不起作用:

#include <iostream>
using namespace std;
int main()
{
    int n;
    cin>>n;

    int i;

    while (i<=n) {

        cin>>i ;
        i++;

    }



}

您的循环与您的需要相去甚远。 您写的内容非常错误,因此除了学习循环、变量和输入的基础知识外,我无法提供建议。 您需要的帮助超出了简单问题/答案的范围,您应该考虑购买一本书并从头到尾阅读。 考虑阅读使用 C++ 的编程原理和实践

这是一个近似于您的问题要求的工作示例。 我将文件输入和输出留给您作为练习。 我还使用了 C++11 的前后 std::string 成员。 在旧版本中,您必须通过数组索引进行访问。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main(){
    int totalWords;
    cin >> totalWords;
    stringstream finalOutput;

    for (int i = 0; i < totalWords; ++i){
        string word;
        cin >> word;
        if (word.length() > 10){
            finalOutput << word.front() << (word.length() - 2) << word.back();
        }else{
            finalOutput << word;
        }
        finalOutput << endl;
    }

    cout << endl << "_____________" << endl << "Output:" << endl;
    cout << finalOutput.str() << endl;
}

话虽如此,让我给你一些建议:

有意义地命名变量。 像我上面那样的 for 循环中的“int i”是一个常见的习惯用法,“i”代表索引。 但通常你想避免将 i 用于其他任何事情。 而不是 n,称之为 totalWords 或类似的东西。

此外,确保所有变量在访问之前都已初始化。 当您第一次进入 while 循环时,我没有定义的值。 这意味着它可以包含任何内容,实际上,您的程序可以任何事情,因为它是未定义的行为。

顺便说一句:为什么你在你的例子中读到一个整数 i ? 那你为什么要增加它? 这样做的目的是什么? 如果您从用户那里读取输入,他们可以输入 0,然后您将其增加 1 将其设置为 1...下一次迭代可能他们会输入 -1,您将其增加 1 并将其设置为 0。 .. 然后他们可以输入 10001451 并且您增加 1 并将其设置为 10001452 ......你看到这里的逻辑问题了吗?

似乎您正在尝试使用 i 作为迭代总数的计数器。 如果您这样做,请不要同时将用户的输入读入 i。 这完全破坏了目的。 在我的示例中使用单独的变量。

你可能想拥有类似的东西:

#include <iostream>

int main() {
    int n;
    cin>>n;
    int theInputNumbers[n];

    for(int i = 0; i<n; ++i) {
        cin >> theInputNumbers[i];
    } 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM