C++将char添加到char[1024]中
C++ add char to char[1024]
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
char command[1024];
char newchar;
cout << "Command Line Interface Test with Intellisense" << endl;
cout << endl;
newchar = _getch();
command = command + newchar;
}
为什么这不起作用?
为什么command=command+newchar是错误的?
您应该使用std::string
和append
作为其字符。http://en.cppreference.com/w/cpp/string/basic_string/append
或者使用C++11,您可以将+=运算符与std::string 一起使用
(您必须#包含字符串标题(
它不起作用,因为C++是静态类型的。char[1024]
对象在其整个生命周期中将保持相同的类型,并且不能更改为char[1025]
。这同样适用于std::string
,但字符串的大小不是其类型的一部分,因此可以更改:
std::string command = "abc";
comamnd += "d";
在command + newchar
中,命令变成了一个(const(指针,newchar是一个整数值,所以您要将指针指向一个"更大"的地址,但在将结果分配给command
时,您要尝试将(const"指针更改为一个数组,幸运的是,这是不允许的。
char* pNew = command + newchar;
这本可以奏效,但没有达到预期效果。正如其他人已经回答的那样:使用std::string。
你想做这样的事情吗?
#include <iostream>
#include <conio.h>
using namespace std;
#define BUFFER_SIZE 1024
int main(){
char command[BUFFER_SIZE];
cout << "Command Line Interface Test with Intellisense" << endl;
cout << endl;
for(unsigned int i = 0; i < BUFFER_SIZE; ++i)
char newchar = _getch();
if(newchar == 'n') break;
// do some magic with newchar if you wish
command[i] = newchar;
}
}