字符串下标超出范围错误"C++"
String subscript out of range error "C++"
此程序将文本文件带入猪拉丁语。我已经完成了所有工作,但继续遇到"下标"的错误。我试图改变很多事情,但不能让它消失。有人可以解释为什么我会遇到这个错误吗?
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
void piglatin ( string word[], string temp, ifstream & in, int num);
int main()
{
string word[300];
string original[300];
string temp;
ifstream in;
int i=0,
j=0,
x=0,
par=0,
length=0;
in.open("text.txt");
if (in.is_open()) { //Checks if file is open
cout << "nFile is open....nnn";
} else {
cout << "Error: Failed to open!n";
cout << "Exiting programn";
exit(-1);
}
cout<<"Original textnn";
do {//Continues while loop until no more input.
in >> original[x];
cout << original[x] << " ";
x++;
par = par + x;
} while (!in.eof());
cout<<"nn";
cout<<"Pig Latinnn";
piglatin(original,temp,in,par);
return 0;
}
void piglatin ( string word[], string temp, ifstream & in, int num)
{
int i=0, length, j=0,a=0;
for(j = 0; j < num; j++) {
string str (word[j]);
length = str.size();
temp[0] = word[j][0];
if ((temp[0] == 'a') ||
(temp[0] == 'e') ||
(temp[0] == 'i') ||
(temp[0] == 'o') ||
(temp[0] == 'u'))
{
word[j] += "way";
} else {
for(i = 0; i <= length-1; i++) {
word[j][i] = word[j][i+1];
}
word[j][length-1] = temp[0];
word[j] += "ay";
}
cout << word[j] << " ";
length = 0;
}
cout << "nn";
}
此语句
temp[0] = word[j][0];
是无效的,因为字符串温度为空,您可能不会使用带有空字符串的下标操作员来存储字符。
您可以在for循环之前写作,例如
temp.resize( 1 );
我也看不到参数温度的任何意义。您可以在函数局部变量 char temp;
中使用弦临时,因为您仅使用temp存储一个字符。
我相信您缺少给ifstream的参数:ifstream对象需要两个参数,一个文件名和一个模式,其中描述了该文件所需的I/O模式。
in.open("text.txt");
应该是:
in.open("text.txt", ifstream::in);
这是ifstream.open的API的链接:http://www.cplusplus.com/reference/fstream/ifstream/open/
相关文章:
- 警告处理为错误这里有什么问题
- "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'