简体   繁体   English

在C ++中使用堆栈和向量以相反的顺序打印字符串

[英]Printing a string in reverse order using stacks and vectors in C++

Quick question: I am trying to accept a string parameter and then print it backwards using stacks and vectors. 快速问题:我试图接受一个字符串参数,然后使用堆栈和向量向后打印它。 However, nothing is printed to the screen after it says Here you go!. 但是,在屏幕上显示“您要走!”之后,什么都没有打印到屏幕上。 I believe it has something to do with the vector setup, as I have never worked with this before. 我相信它与矢量设置有关,因为我以前从未使用过它。 Here is the code in question. 这是有问题的代码。 I would appreciate any help! 我将不胜感激任何帮助!

void main() {

stack<char> S;
string line;
vector<char> putThingsHere(line.begin(), line.end());
vector<char>::iterator it;

cout << "Insert a string that you want to see backwards!" << endl;
cin >> line;

for(it = putThingsHere.begin(); it != putThingsHere.end(); it++){
    S.push(*it);
}

cout << "Here you go! " << endl; 

while(!S.empty()) {
    cout << S.top();
    S.pop();
}

system("pause");


}

Your vector is being initialized too early, when line is still empty. line仍然为空时,向量初始化太早。 Move the construction of putThingsHere below the instruction that extracts the string from the standard input: putThingsHere的结构putThingsHere从标准输入中提取字符串的指令下面

cin >> line;
vector<char> putThingsHere(line.begin(), line.end());

Here is a live example of your fixed program running correctly. 这是固定程序正确运行的实时示例

Notice the use of getline() instead of cin >> line , so that whitespaces in between your characters could still be read as part of one single string. 请注意,使用getline()代替了cin >> line ,因此字符之间的空格仍可以作为一个字符串的一部分来读取。

This said, it is worth mentioning that std::string satisfies the requirements of standard sequence containers and, in particular, has member functions begin() and end() returning an std::string::iterator . 这就是说,值得一提的是std::string满足标准序列容器的要求,尤其是具有成员函数begin()end()返回std::string::iterator

Therefore, you do not need an std::vector<> at all and the snippet below will do the job: 因此,您根本不需要std::vector<> ,下面的代码段就可以完成工作:

getline(cin, line);
for(std::string::iterator it = line.begin(); it != line.end(); it++) {
    S.push(*it);
}

Your line variable is initially empty. 您的line变量最初为空。 You never really put anything inside the vector PutThingsHere and stack S. 您永远不会真正在vector PutThingsHere和stack S内放入任何东西。

Put the 放在

cout << "Insert a string that you want to see backwards!" << endl;
cin >> line;

before the vector<char> PutThingsHere(...) statement. vector<char> PutThingsHere(...)语句之前。

First read into line and only then putThingsTHere 首先读入line ,然后putThingsTHere

stack<char> S;
string line;

cout << "Insert a string that you want to see backwards!" << endl;
cin >> line;
vector<char> putThingsHere(line.begin(), line.end());
vector<char>::iterator it;

我已经在使用std::string了,为什么不使用:

`std::string reversed(line.rend(), line.rbegin());`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM