C++ substr out_of_range error

C++ substr out_of_range error

本文关键字:range error of C++ out substr      更新时间:2023-10-16

我是C++语言的新手,我一直在寻找我问题的明确答案,但没有结果。我正在尝试做的是获取文本文件中单行字符串的值substr。当我像这样运行编译时,我收到句子的前十二个字母,我对此没有问题:

a[count] = sentence.substr(0,12);

但是当我尝试将pos0更改为任何其他值时,例如:

a[count] = sentence.substr(1,12);

我收到错误:

在抛出 std::out_of_range 实例后终止调用 what((: basic_string::substr: _pos (即 1( this -> size(( (即 0(

我用YT和在线指南检查了一下,没有人对substr有问题。 有什么想法吗?

编辑: 很抱歉造成混乱。这是代码的一部分:

string sentence;
string a[10000];
string next_line[10000];
main()
{
int count = 1;    

fstream file;
file.open("converted.txt",ios::in);
while(!file.eof())
{
getline(file, line);
next_line[count] = line;
sentence = next_line[count];
a[count] = sentence.substr(1,12);
count++;
}
}

来自 feof

此指标通常由流上的先前操作设置 试图在文件末尾或文件末尾读取。

这意味着在条件为 false 之前,您已经读取了另一行。 此行为空

从子斯特

子字符串是对象中以字符开头的部分 定位 POS 和跨度 len 字符(或直到字符串末尾, 以先到者为准(。

因此,如果您将substr与第一个参数 0 一起使用,没关系,它被跳过了。但是,如果您将 1 作为第一个参数传递,这比字符串包含字符更多,则会引发异常。


这是从文件中正确读取的内容

#include <iostream>
#include <fstream>
using namespace std;
string sentence;
string a[10000];
string next_line[10000];
int main()
{
int count = 1;
std::string line;
fstream file;
file.open("test.txt",ios::in);
while(getline(file, line))
{
next_line[count] = line;
sentence = next_line[count];
a[count] = sentence.substr(1,12);
count++;
}
}
相关文章: