2012-03-20 44 views
1

我试图编写一个程序,它将字符串中的消息存储回字符数组中,并且每当我运行它时,它有时会成功向后写入,但有时会将随机字符添加到末尾此:Random ascii char的出现

输入:写这个向后

sdrawkcab SIHT etirw

#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
string message; 
getline(cin, message); 
int howLong = message.length() - 1; 
char reverse[howLong]; 
for(int spot = 0; howLong >= 0; howLong--) 
{ 
    reverse[spot] = message.at(howLong); 
    spot++; 
} 
cout << reverse; 
return 0; 
} 
+6

C++不支持VLA – ipc 2012-03-20 16:11:58

回答

4

缓冲reverse需要是message.length() + 1在长度,使得它能够存储一个空终止字节。 (并且空终止字节需要放在该缓冲区的最后一个位置。)

+0

'char reverse [howLong]'会做什么?编译器如何为动态长度的char []分配空间?它编译没有ideone问题 - 我必须缺少一些东西:\ [或者它是UB吗?] – amit 2012-03-20 16:12:31

+0

@amit,我认为这是一个GCC扩展与C99兼容。 – 2012-03-20 16:14:01

2

由于您无法声明仅在运行时已知的长度的数组,因此必须使用容器。

std::vector<char> reverse(message.length()); 

或更好,请使用std::string。该STL还提供了一些不错的功能给你,例如建立反向字符串中的构造函数调用:

std::string reverse(message.rbegin(), message.rend(); 
1

倒车入字符缓冲区相反的,你应该建立一个新的字符串。它更容易,更不易发生错误。

string reverse; 
for(howlong; howLong >= 0; howLong--) 
{ 
    reverse.push_back(message.at(howLong)); 
} 
1

使用适当的C++解决方案。

内嵌扭转消息:

#include <iostream> 
#include <string> 
#include <algorithm> 

using namespace std; 

int main() { 
    string message; 
    getline(cin, message); 

    //inline reverse the message 
    reverse(message.begin(),message.end()); 

    //print the reversed message: 
    cout << message << endl; 
    return 0; 
} 

反向消息字符串的副本:

#include <iostream> 
#include <string> 
#include <algorithm> 

using namespace std; 

int main() { 
    string message, reversed_message; 
    getline(cin, message); 

    //reverse message 
    reversed_message = message; 
    reverse(reversed_message.begin(), reversed_message.end()); 

    //print the reversed message: 
    cout << reversed_message << endl; 
    return 0; 
} 

如果你真的需要反向字符串保存在C字符串,你可以这样做:

char *msg = (char *)message.c_str(); 

但是,根据经验,如果可以,请使用C++ STL字符串。