c++ - 带有字符显示的 vector

标签 c++ arrays string io formatting

我在显示寄存器中输入的数据时遇到问题。我编写的以下程序仅显示最后一个寄存器。( ziua=day , inregistrari=registers, data=date (ex. 03.02.2013))

#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
    char ziua[30],data[30],inregistrari[90];
    int n,i;
    cout<<"INPUT DATA"<<endl;
    system("Pause");
    cout<<"\nEnter the day in which you want to perform the register: ";
    cin>>ziua;
    cout<<"\nDATE:";
    cin>>data;
    cout<<"\nEnter the number of registers you wanna perfom for the day "<<ziua<<":";
    cin>>n;
    for(i=1;i<=n;i++)
    {
        cout<<"\nRegister "<<i<<":";
        gets(inregistrari);
    }
    cout<<"The data for the day of "<<ziua<<" are the following: ";
    cout<<"\nDATE: "<<data;
    for(i=1;i<=n;i++)
    cout<<"\n"<<inregistrari;
    getch();
}

最佳答案

  1. 你正在用 C++ 编程,你应该使用 std::string而不是 C 风格的字符串。
  2. inregistrari[90]是一个字符数组,大到足以容纳 1 个最大长度为 89 的字符串 char s(+ 终止字符),但您的循环似乎将其视为数组或字符串(尽管在这种情况下 gets(inregistrari); 继续重写相同的字符串)
  3. 函数gets通常不推荐使用,在 C 中你应该使用 fgets相反(但这是 C++,因此这里真正的解决方案应该使用 std::getline )
  4. 使用 std::vector<std::string> 而不是 C 风格的数组在这里。
  5. 打印inregistrarifor 的正文中循环,但此循环的每次迭代都做完全相同的事情(打印不以任何方式依赖于 i)
  6. using namespace std;在全局空间内是一种不好的做法
  7. 您不必在函数的开头声明所有变量,这在旧的 ANSI C 中是必需的(大约 20 年前)

这是一个例子,它看起来像这样:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::string day, date;
    int registerCount;

    std::cout << "INPUT DATA"
              << std::endl << std::endl
              << "Enter the day in which you want to perform the register: "
              << std::endl;
    std::cin >> day;
    std::cout << "DATE:" << std::endl;
    std::cin >> date;
    std::cout << "Enter the number of registers you wanna perfom for the day "
              << day << ":" << std::endl;
    std::cin >> registerCount;

    std::vector<std::string> registers(registerCount);
    for (int i = 0; i < registerCount; ++i)
    {
        std::cout << "Register " << i << ":" << std::endl;
        std::getline(std::cin, registers[i]);
    }

    std::cout << "The data for the day of " << day << " are the following: "
              << std::endl;

    std::cout << "DATE: " << date << std::endl;
    for (int i = 0; i < registerCount; ++i)
        std::cout << registers[i] << std::endl;
}

请注意,您可能会将 std::getline(std::cin, registers[i]) 换行与 if声明并检查是否已返回有效的流对象,如果是空行,它将读取空字符串,因此您还可以确保 !registers[i].empty() .

关于c++ - 带有字符显示的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615387/

相关文章:

C++:模板实现(代码风格)

c++ - 在 C++ 中使用 pthreads 实现线程池

c++ - 从 DLL 导出 ASM 函数 - Visual Studio C++

javascript - 在 JavaScript 中重复一个字符串多次

c++ - Qt 5 构建错误 : extra characters after test expression

java - 数组中元素的总和

c# - C# 中的数组切片

php - glob() - 按上次修改的日期时间戳对文件数组进行排序

javascript - 调整表格大小时如何通过在字符串中间放置省略号来 chop 字符串

javascript 无法识别空格字符