【发布时间】:2020-05-09 15:16:08
【问题描述】:
我只想知道这段 C++ 代码有什么问题: 我必须从控制台获取字符并计算写了多少行。然后我必须以相反的顺序显示它们。即:如果我写 3 行:“hi”、“im”、“lucas”,每行都以 '\n' 结尾。我必须把它们颠倒过来,所以它会一行一行地写“lucas”、“im”、“hi”。 首先,我将这些行“保存”在“字符串”向量中,然后用一个从结尾到开头的迭代器显示它们。 我将 VSCode 与 g++ 一起使用,最终迭代器向量循环似乎存在问题。程序停在那里并抛出一个 SIGINT 中断。 为什么会这样?如何纠正?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string strLines = "";
int c;
do {
c = getc(stdin);
strLines += c;
} while (c != EOF);
size_t oldIndex = 0;
size_t newIndex;
int totalStrings = 0;
vector<string> strVector;
while (1)
{
newIndex = strLines.find('\n', oldIndex);
if (newIndex == string::npos)
break;
string strToPush = strLines.substr(oldIndex, newIndex+1);
strVector.push_back(strToPush + '\0');
oldIndex = newIndex+1;
totalStrings++;
}
//reverse string
for (vector<string>::iterator it = strVector.end()-1 ; it != strVector.begin(); it--)
{
string strShow = *it;
cout << *it;
}
c = getchar();
return EXIT_SUCCESS;
}
【问题讨论】:
-
一个堆栈会更好。
-
你甚至没有向后迭代。为什么有一个 totalStrings 变量?你从不使用它,向量知道它们有多大。
标签: c++ vector iterator console