【问题标题】:Getting multiple lines of input in C++在 C++ 中获取多行输入
【发布时间】:2014-06-02 07:17:48
【问题描述】:

第一行包含一个整数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++;

    }



}

【问题讨论】:

  • cin&gt;&gt;i ; i++; Aawww! 这看起来很奇怪:-/ ...
  • 您想如何存储该输入?
  • 如果您只想阅读它,这将起作用#include &lt;iostream&gt; using namespace std; int main() { int n; cin&gt;&gt;n; int i=0; string xd; while (i&lt;=n) { cin&gt;&gt;xd ; i++; } } 它会一次读取一个单词,并将它们存储在字符串“xd”中。您可以选择将其附加到其他内容,将其放入 [i] 元素的字符串数组中,或者您想要的任何其他内容。
  • @random21 cmets 中的代码是如此 baaaad!你为什么不写一个答案?
  • 因为这么简单的程序不值得被认为是答案。

标签: c++ input while-loop


【解决方案1】:

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

#include <iostream>

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

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

【讨论】:

    【解决方案2】:

    你的循环真的离你需要的很远。您写的内容非常错误,因此除了学习循环、变量和输入的基础知识之外,我无法提供建议。您需要的帮助超出了简单问题/答案的范围,您应该考虑购买一本书并从头到尾阅读。考虑阅读Programming Principles and Practice Using 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。这完全破坏了目的。在我的示例中使用单独的变量。

    【讨论】:

      猜你喜欢
      • 2019-09-09
      • 1970-01-01
      • 2014-06-24
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多