我想从字符串句子中取出单词并在 C++ 中得到此错误
i want to take out words from a string sentence and get this error in c++
#include<iostream>
#include<string>
using namespace std;
void extractFirstWord(string& sentence, string& word);
void processBlanks(string& sentence);
int main() {
string sentence, word;
cout << "Input a sentence: ";
getline(cin, sentence);
while (sentence != "") {
processBlanks(sentence); // removes all blanks from the front of sentence
if (sentence.length() > 0) { // removing blanks may have made sentence null - cannot extract from a null string
extractFirstWord(sentence, word); // gets first word from sentence and puts into word
cout << word << endl; // output one word at a time
}
}
system("PAUSE");
return 0;
}
void extractFirstWord(string& sentence, string& word)
{
int i=0;
while(sentence[i]!=' ')
{
i++;
}
word=sentence.substr(0,i);
sentence=sentence.substr(i);
}
// extractFirstWord removes the substring of sentence
// from the beginning to the first space from sentence
// and stores the same string into word. sentence is
// shortened accordingly.
// Postcondition: sentence is shortened, and word
// is appropriately the first word in
// sentence.
void processBlanks(string& sentence)
{
int i=0;
while(sentence[i]==' '){i++;}
sentence=sentence.substr(i);
}
processBlanks 将删除句子前面的所有空格。后置条件:句子在第一个单词前面没有空格。
我想从字符串句子中取出单词并在 C++ 中得到此错误
错误是 -> 字符串下标超出范围
在extractFirstWord
中,如果您还没有找到空间,您会不断增加i
。但是,如果字符串是字符串中的最后一个单词,则可以索引超过字符串的末尾。更改while
条件,如下所示:
while(i < sentence.length() && sentence[i]!=' ')
只需考虑输入没有空格的情况,您的变量 i 将递增直到单词长度,在这种情况下,它将超出范围。 尝试在 substr(( 方法之前检查 i 是否等于单词长度
使用 stringstream
#include <iostream>
#include <sstream>
int main(){
std::stringstream ss(" first second. ");
std::string word;
ss >> word;
std::cout << word << std::endl;//first
}
void extractFirstWord(string& sentence, string& word)
{
int i=0;
while(i<sentence.size() && sentence[i]!=' ') // i should be less than sentence size
{
i++;
}
word=sentence.substr(0,i);
sentence=sentence.substr(i);
}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'