我试图将输入作为一个字符数组并进行操作。例如,这就是我所拥有的。但我刚开始使用数组,我很困惑我应该如何存储char数组。
void getMessage(char message[CHARACTERS])
{
int i = 0;
cout << "Enter message: ";
for (i = 0; i < CHARACTERS; i++)
{
cin >> message[i];
if (message[i] == NULL)
break;
}
cout << "The message you entered was:" << endl << message[i] << endl;
}
字符等于常数100,因为我不知道数组的大小,它基于用户输入。当我尝试将数组输出时,它不会。
答案 0 :(得分:2)
你在这里混淆了:
if (message[i] == NULL)
在C ++中,NULL
被定义为一个宏并扩展为零,所以你实际测试的是
if (message[i] == 0)
如果您从终端或文本文件输入(这肯定不是以这种方式读取二进制文件,这几乎是不可能的!)。根据您的需要将其更改为下面的任何一个,然后它应该可以工作。
// Input a line
if (message[i] == '\n') {
message[i] = '\0'; // strip the newline
break;
}
// Input until something goes wrong
if (cin.fail()) {
message[i] = '\0';
break;
}
// Or combine them:
if (message[i] == '\n' || cin.fail()) {
message[i] = '\0';
break;
}
记住终止字符串也是一种好方法,以防你读取所有缓冲区并且cout
将在零字符之前输出所有内容,这是潜在的访问冲突:
for (...) {...}
message[CHARACTERS - 1] = '\0'.
此外,您的输出语句也是错误的:
cout << "The message you entered was:" << endl << message[i] << endl;
您只是按message[i]
输出一个字符。如果要输出整个消息,请删除数组索引运算符:
... << message << ....
这样您就可以使用ostream& operator <<(const char*)
重载来输出字符串。
答案 1 :(得分:1)
所以把所有这些放在一起,显而易见的现代C ++方式来做你想做的事情:
#include <cstddef>
#include <iostream>
#include <memory>
using std::cout;
using std::flush;
using std::endl;
using std::cin;
using std::size_t;
template <size_t CHARACTERS>
void getMessage(char(& message)[CHARACTERS]) {
int i = 0;
cout << "Enter message: " << flush;
for (i = 0; i < CHARACTERS; i++) {
if (!cin.get(message[i])
|| message[i] == '\0'
|| message[i] == '\r'
|| message[i] == '\n') {
message[i] = '\0';
break;
}
}
cout << "The message you entered was:" << endl << message << endl;
}
int main() {
char message[200];
getMessage(message);
return EXIT_SUCCESS;
}
答案 2 :(得分:-1)
// Example program
#include <iostream>
#include <string>
using namespace std;
const int CHARACTERS = 100;
void getMessage(char message[CHARACTERS])
{
int i = 0;
cout << "Enter message: ";
for (i = 0; i < CHARACTERS-1; i++)
{
message[i] = cin.get(); // cin >> message[i] can't detect enter press as was in your case, so you need to use a lower level function like cin.get()
if (message[i] == '\n'){
message[i+1] = '\0'; // This is a c++ marker for end of string otherwise garbage values will print
break;
}
}
cout << "The message you entered was:" << endl << message << endl; //You were printing only one letter of the message
}
int main()
{
char inputArray[CHARACTERS];
getMessage(inputArray);
}
在线运行:http://cpp.sh/6rh3w