【问题标题】:is there is a way to add a number of lines the user enter using c++?有没有办法添加用户使用 C++ 输入的行数?
【发布时间】:2020-04-07 22:10:41
【问题描述】:

我尝试使用动态字符串数组来制作它,但是当我尝试添加 2 行时,它只添加了 1 行,我不知道为什么 这是我的代码

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    int x;
    string name;
    string* lines;
    cout << "Input the file name to be opened : ";
    cin >> name;
    cout << endl << "Input the number of lines to be written : ";
    cin >> x;
    lines = new string[x];
    cout << endl << "The lines are :";
    for (int i = 0; i < x; i++)
    {
        getline(cin,lines[i]);
    }
    fstream File(name, ios::out | ios::app);
    for (int i = 0; i < x; i++)
    {
        File << lines[i] << endl;
    }
    File.close();
}

它给了我这个警告: C6385 从 'lines' 读取无效数据:可读大小为 '(unsigned int)*28+4' 字节,但可能读取 '56' 字节

【问题讨论】:

  • 不用担心,使用std::vector&lt;std::string&gt;。它将减轻您遇到的问题。
  • 或者,只需在阅读文件时将每一行附加到文件(在输入循环中)。该程序显然不需要将所有行存储在内存中。
  • 另请注意,在cin &gt;&gt; x 之后,整数输入后面的任何额外空格或字符(包括换行符)仍将是未读的。当您调用getline 时,这些字符将构成第一行,因此如果您输入一个数字并按 Enter,则读取的第一行将为空。
  • 请注意,以上内容并不意味着在您的代码周围撒上“以防万一”cin.ignore()s。如果您需要ignore,请在将您需要的内容留在流中的操作之后执行。如果您在读取之前抢先放置ignore,迟早您会发现没有您想要忽略的任何内容,而是您不小心删除了您确实想要的输入。
  • @user4581301 @paddy 正如你们俩所说我尝试在getline 之前使用cin.ignore() 它仅适用于第一行,但它从第二行删除了一个字母,所以我使用此代码` (int i = 0; i

标签: c++


【解决方案1】:

要存储您的字符串,您可以使用std::vector,它是一个可变大小的 C++ 容器,比 C 类型数组更受欢迎,下面是 cmets 的示例:

Live sample

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>

using namespace std; //for test purposes, in real code you shoud use std:: scope

int main()
{
    int x;
    string name, line;
    vector<string> lines; //container

    cout << "Input the file name to be opened : ";
    cin >> name;

    fstream File(name, ios::app | ios::out);

    cout << endl
         << "Input the number of lines to be written : ";
    cin >> x;
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); //needed because getline does not ignore new line characters
                                                         //explicitly looking to clear buffer till '\n', improves clarity
    cout << endl
         << "The lines are :";

    while (x > 0)
    {
        getline(cin, line);
        lines.push_back(line); //add lines to vector, this is assuming you need the lines in memory
        x--;                   //otherwise you could save them directly to the file
    }

    if (File.is_open())
    {
        for (string s : lines)  //writing all the lines to file
        {
            File << s << endl;
        }
        File.close();
    }
}

【讨论】:

  • 这个答案在正确的位置有ignore()。看看这有多容易?加上与cin &gt;&gt; x; 非常接近的ignore,这种关系更加明显。我唯一会做的不同是明确表示我们正在寻找古怪的换行符并用cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n')吃掉任何其他碎片@
  • @user4581301,是的,我认为这是一种改进。
猜你喜欢
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 2023-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-03
相关资源
最近更新 更多