C++Integer从*char[]中删除字符串
C++ Integer removes string from *char[]
我正试图在C++程序中读入几个值。
当我输入一个1位数的数字(在我的代码底部)时,我就没事了。
但是,如果我输入一个2位数的数字,比如"10",消息(我输入的第二个数字)就会被擦除。
这是我的代码:
char * args[6];
unsigned time = 5;
char input[5]; // for string input
string message= "message";
//these strings and *chars are tempary strings for the purpose of reading in data
string temp;
char *temp2 = " ";
char *temp3 = "empty pointer";
args[count] = "-m";
count ++;
//Prompt for the message
cout <<endl<<"Alright, Please enter your message: "<<flush;
getline(cin, message);
cout <<endl<<endl;
message.append(""");
message = """+message;
//we can't use the string, so we copy it to temp3.
strcpy(temp3, message.c_str());
//Now we input the string into our array of arguments
args[count] = temp3;
count ++;
cout <<"Please enter time "<<flush;
getline(cin,temp);
//validate input utnil its an actual second.
bool done = false;
while (done == false){
for(unsigned i = 0; i < temp.length() & i < 5; i++){
input[i] = temp[i];
}
done = CheckInteger(input, input);
time = atoi(input);
if (done == true & time < 1) {
cout <<"Unable to use a number less than 1 seconds! "<<endl;
cout <<"Please enter the number of seconds? "<<flush;
done = false;
}else if (done == false){
cout <<"Please enter the number of seconds? "<<flush;
}else{
break;
}
getline(cin,temp);
}
cout <<endl<<endl;
time = atoi(input);
//timer argument
args[count] = "-t";
count ++;
// enter the time need to comvert from int to string.
ostringstream convert;
convert <<time;
temp = convert.str();
//need to convert from string to character
strcpy(temp2, temp.c_str());
args[count] = temp2;
count ++;
我该怎么解决这个问题?
strcpy(char* destination, const char* source)
将source
字符串复制到destination
指向的数组中。但是您调用的是strcpy(temp3, message.c_str());
,它试图将字符串复制到指向常量字符串文字的指针中:char *temp3 = "empty pointer";
,这将导致未定义的行为[1]
将temp3
从指针更改为将使用以下字符串文字初始化的数组:
char temp3[] = "empty pointer";
或者更好:使用std::string
。
[1] C++03标准2.13.4字符串文字(选定部分):
§1普通字符串文字的类型为"n
const char
的数组",静态存储持续时间为§2试图修改字符串文字的效果是未定义的
相关文章:
- 如何删除字符串中的前 2 个字符(如果它有"-")
- 删除字符串后C++检测到堆损坏
- 如何在 c++ 中删除字符串中的某些字符?
- 删除字符串数组
- 删除字符串中具有相同值的任何相邻字母"pair"
- 删除字符串向量中的字符重复
- 如何在Qt中删除字符串(qstring)中的子字符串
- 删除字符串指针在struct中的内存
- 删除 C 字符串中的大写字母
- 如何搜索和删除字符串中的字符
- 如何删除字符串中的所有空格并将数据存储在两者之间
- 删除字符串中不平衡的括号
- 删除字符串数组中的换行符
- 如何修复我的代码以删除字符串中的空格
- 如何删除字符串所有可能的子字符串中带有空格的子字符串?
- 如何创建删除 C 字符串中所有选定字符的函数
- 传递GTK回调时,请在C 中删除字符串向量
- 为什么删除字符串迭代器会产生const char参考
- 从<string>向量<int>中定义的索引处的向量中删除字符串
- 如何使用 c++ 剪切或删除字符串中的某些字符