Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ “错误”;字符串下标超出范围“;_C++_String - Fatal编程技术网

C++ “错误”;字符串下标超出范围“;

C++ “错误”;字符串下标超出范围“;,c++,string,C++,String,运行这些代码时遇到错误“字符串下标超出范围” #include <iostream> #include <string> #include <fstream> using namespace std; int main () { ifstream in("_start.txt"); ofstream out("_end.txt"); string str; while (getline(in, str)) {

运行这些代码时遇到错误“字符串下标超出范围”

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

int main ()
{
    ifstream in("_start.txt");
    ofstream out("_end.txt");

    string str;
    while (getline(in, str))
    {
        if ((str[0] != '/') && (str[1] != '/'))
            out << str << endl;     
    }

    //getline(in, str);
    //if ((str[0] != '/') && (str[1] != '/'))
        //out << str << endl;
    return 0;
}
或更大的前一行的数字2,3或4,。。。(大于1)将被固定

这是一段很长的路,所以我从mini开始,目的是打印除开头带有“/”字符的行之外的所有行,我遇到了这个错误。若我并没有循环,第一行的一切都很好,但当我包含循环时,会出现错误

if((str[0] != '/') && (str[1] != '/'))
//                 ^^
//         btw, this should be ||
将在空行和包含单个
/
且没有其他字符的行上调用未定义的行为。
添加此检查():

这可能更容易理解。读作:

首先,检查
str
是否至少有两个字符。如果是,请检查前两个是否为
/
。如果此条件产生
false
,请执行以下代码

还可以使用
std::string::substr
实现更短的代码:

if(str.length() < 2 || str.substr(0, 2) != "//")

是什么让您确保访问
str[1]
有效地在实际边界内?如果我在VS无循环的情况下使用“Step over”进行调试,“str”值VS显示第一行,如果使用循环但没有“If语句”,VS显示每个循环后的每一行。我认为如果我在循环中添加“if”是可以的,但是出现了错误。非常感谢。我是新的C++,所以我错过了空行。注意:自从C++ 11,长度检查实际上不是必需的;code>str[str.size()]是指存储在某处的只读空终止符,如果
str[0]
确实是空终止符,则短路将阻止尝试
str[1]
Add "//-character" at start of previous line
if((str[0] != '/') && (str[1] != '/'))
//                 ^^
//         btw, this should be ||
if(str.length() < 2 || (str[0] != '/') || (str[1] != '/'))
if(!(str.length() >= 2 && str[0] == '/' && str[1] == '/'))
if(str.length() < 2 || str.substr(0, 2) != "//")
if(!(str.length() >= 2 && str.substr(0, 2) == "//"))