c++ - getline 没有为字符串对象赋值

标签 c++ runtime-error getline

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

int main()
{
//YOUR_CODE
string word;

cout << "enter a word: ";
getline(cin, word);
int middle = word.length();
middle = middle/2;
if(middle % 2 == 0)
{
    middle = word.length();
    middle = (middle/2)+1;
    floor (middle);
}
int last = word.length();
cout << word[0] << word.at(middle) << word.at(last);
}

我不确定为什么 getline 不工作。检查我正在使用的书,调试器没有帮助。有谁知道它有什么问题?在调试器中,它显示值:<不可访问>。任何帮助表示赞赏。

最佳答案

word 的赋值没有问题。问题是 word.at(last)。字符串位置从 0length-1(就像数组一样)。由于 lastword.length(),您正试图访问该范围之外的字符。尝试:

last = word.length()-1;

关于c++ - getline 没有为字符串对象赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21640475/

相关文章:

c++ - (相对)C++ 中大小安全的包装 STL 容器

c++ - 将 istream 运算符 >> 转换为 istream getline

C++ getline() 不在行尾停止?

date - getline,awk和日期(格式化日期)

c++ - 我们可以在另一个成员函数的参数列表中使用一个成员函数的decltype吗?

c++ - 是否有可能从 cin 中读取一个空字符串并仍然从 cin.good() 中得到 true?

c++ - 链接 GLEW 和其他人,_glViewport 是唯一 Unresolved

python - Python 中对象名称的奇怪错误

sql - sql golang执行查询时无效的内存地址或nil指针取消引用

angular - take is not a function : Angular 7 | Observable. take 抛出运行时错误