字符串下标超出范围错误"C++"

String subscript out of range error "C++"

本文关键字:错误 C++ 范围 下标 字符串      更新时间:2023-10-16

此程序将文本文件带入猪拉丁语。我已经完成了所有工作,但继续遇到"下标"的错误。我试图改变很多事情,但不能让它消失。有人可以解释为什么我会遇到这个错误吗?

#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/