簡體   English   中英

使用 c++,為什么我明知不是,卻收到錯誤消息“字符串下標超出范圍”? 或者至少看起來是這樣

[英]Using c++, why am I getting the error message "string subscript out of range" when I know it is not? Or at least it seems that way

編輯 - 沒有空行。 編輯 2 - 我的錯,看來我一直都錯了。 某處有一個空行,盡管 csv 文件另有說明。 它現在正在工作。 好的,這是整個(簡短的)程序:

#include <iostream>
#include <cctype>
#include <string>
#include <fstream>
using namespace std;

int main(){
    char a;
    string stringmanip;

    fstream myfile("readthisfile.csv");
    if (myfile.is_open()){
        while ( myfile.good() ){
            getline(myfile,stringmanip);
            a=stringmanip[0];
        }
        myfile.close();
    }
    else cout<< "Unable to open file";

    return 0;
}

對我來說完全是無稽之談。 我可以復制 stringmanip,我可以 cout stringmanip,我可以將 .substr 與 stringmanip 一起使用。 如果我定義一個常規字符串,我可以很好地使用 [] 操作。 我也試過了,但這只會導致另一個錯誤。 (超出范圍)。

任何幫助將不勝感激。 對不起,我是一個初學者,我相信你能看出來。

謝謝,本

如果 readthisfile.csv 在文件末尾(或文件中的任何位置)有一個空行,那么您將返回一個空字符串。 您不能取消引用空字符串的第 0 個字符。 string::operator[]只接受從0string::length() - 1的索引。 如果您有一個空字符串,則對string::operator[]的任何調用都將導致未定義的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM