C++ substr out_of_range error
C++ substr out_of_range error
我是C++语言的新手,我一直在寻找我问题的明确答案,但没有结果。我正在尝试做的是获取文本文件中单行字符串的值substr
。当我像这样运行编译时,我收到句子的前十二个字母,我对此没有问题:
a[count] = sentence.substr(0,12);
但是当我尝试将pos
从0
更改为任何其他值时,例如:
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++;
}
}
相关文章:
- "error: no matching function for call to"构造函数错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 使用 LuaBridge 将 LuaJIT 绑定到C++会导致"PANIC: unprotected error"
- OpenMP卸载说'fatal error: could not find accel/nvptx-none/mkoffload'
- C++错误:"error: int aaa::bbb is protected within this context"
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 使用 cmake 的 LLVM 构建在 tsan_libdispatch_mac.cc 期间失败; "Error: conflicting types for ..."
- C++ "error: invalid use of void expression"
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 如何修复"error: ‘_1’ was not declared in this scope"?
- 从不同目录执行时"symbol lookup error:",否则从构建目录执行时按预期工作
- 对象声明中的模板"error: expected expression"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- OpenCV 3.4.1 error readNetFromTensorflow 无法在 cv::d nn::ReadProtoFromBinaryFile 中打开 .pb
- 已解决 - C++ 的崇高文本中的"fatal error: opencv: no such file or directory"
- 为什么我会"error: expected expression"?
- CMake Error at modules/videoio/cmake/detect_ffmpeg.cmake:16
- 我正在"string subscript out of range error".我不知道为什么
- 每次调试此代码时,我都会得到"subscript out of range error"。有人可以帮我查明一个或多个错误吗?