显示字符的矢量
vector with characters displaying
我在显示寄存器中输入的数据时遇到问题。我编写的以下程序仅显示最后一个寄存器。( ziua=day , inregistrari=registers, data=date (例如 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();
}
- 您正在用C++编程,您应该使用
std::string
而不是 C 样式的字符串。 -
inregistrari[90]
是一个足够大的字符数组,可以容纳 1 个最大长度为 89char
s 的字符串(+终止字符),但您的循环似乎将其视为一个或多个数组(尽管在这种情况下gets(inregistrari);
继续重写相同的字符串) - 函数
gets
通常不推荐使用,在 C 中您应该使用fgets
代替(但这C++,因此这里真正的解决方案应该是使用std::getline
) - 此处使用
std::vector<std::string>
,而不是 C 样式数组。 - 打印
inregistrari
位于for
循环的主体中,但此循环的每次迭代都执行完全相同的操作(打印不以任何方式依赖于i
) - 在全球空间内
using namespace std;
是一种不好的做法 - 您不必在函数的开头声明所有变量,这在旧的 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;
}
请注意,您可以使用if
语句包装std::getline(std::cin, registers[i])
并检查是否返回了有效的流对象,如果是空行,它将读取空字符串,因此您也可以确保!registers[i].empty()
。
相关文章:
- 字符串-C++后显示的随机字符
- 显示基于用户输入的整数的字符
- 在将字符插入 2d 字符串时如何不显示空字符?
- 为什么strlen(s)与s的大小不同,为什么cout-char显示的是字符而不是数字
- 为什么C++在将浮点数转换为字符时没有显示缩小转换错误?
- 链表显示垃圾字符
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 程序,它接受用户输入的字符并按出现的降序显示它们
- 使用带有诅咒库的 stdscr 创建窗口,在边框而不是线条中显示不需要的笑脸字符
- 如何检查输入是否为字符并显示它是"invalid input",否则它将按原样运行
- 如何在不将其转换为 ASCII 字符的情况下显示 QByteArray 的十六进制值
- 如何从显示板将字符显示为字符串?
- 将终端设置为原始模式:仅在按下下一个键后显示字符
- 在QLineEdit中显示和编辑转义字符
- 我的程序没有将字符显示在屏幕上
- C++控制台字符显示
- C++特殊字符显示为"?"
- 将字符显示为没有显式强制转换的整数
- 为什么sizeof为一个字符显示4个字节
- 使用'uxxxx'格式定义的字符显示错误的字符