C ++将char添加到char [1024]

时间:2014-04-18 06:40:01

标签: c++ char

#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是错误的?

4 个答案:

答案 0 :(得分:3)

您应该使用std::stringappend字符。 http://en.cppreference.com/w/cpp/string/basic_string/append

或者使用C ++ 11,您可以将+ =运算符与std :: string

一起使用

(你必须#include字符串标题)

答案 1 :(得分:0)

command + newchar中,命令变为(const)指针而newchar是一个整数值,所以你要指向一个更大的&#34;更大的&#34;地址,但在将结果分配给command时,您试图将(const)指针更改为数组,幸运的是不允许这样做。

char* pNew = command + newchar;

这可行,但没有按预期进行。正如其他人已经回答:使用std :: string。

答案 2 :(得分:0)

它不起作用,因为C ++是静态类型的。 char[1024]对象在其整个生命周期中将保持相同的类型,并且不能更改为char[1025]。这同样适用于std::string,但字符串的 size 不属于其类型,因此可以更改:

std::string command = "abc";
comamnd += "d";

答案 3 :(得分:0)

您是否正在尝试这样做?

#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;
    }

}