字符串下标超出范围c++
string subscript out of range c++
我需要有关非常基本的 C++ 代码的帮助。
我的程序是关于猜名游戏,我遇到的问题是通过 char
读取字符串 char
#include <iostream>
#include <time.h>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
void Play(int, int,int, string[], string[]);
string GetRandomName(int, int, int , string[], string[]);
const int ArrayMax = 100;
void Play(int selection, int FArraySize, int MArraySize,string Female[], string Male[])
{
int MAX_TRIES = 3;
int i=0;
ofstream ofFile;
ifstream InFile;
int num_of_wrong_guesses=0;
char letter;
string GuessedName;
GuessedName = GetRandomName(selection, FArraySize, MArraySize, Female, Male);
cout << "Guess the following name:" << endl;
while (GuessedName[i]!= 0 ){
cout<<"?";
i++;
}
cout << "\nEnter a guess letter? or * to enter the entire name" << endl;
cin >> letter;
return;
}
我没有完成编码...
问题出在while循环中,不使用cstring如何解决?
你能帮帮我吗?
像这样更改 while 循环:
while (GuessedName[i]){
cout<<"?";
i++;
}
int i = 0;
while(GuessedName[i] != 0)
{
cout << "?";
i++;
}
似乎您正在尝试打印 ?
的序列以及要猜测的字符串长度。但是您不能将 std::string
视为 C 字符串。当其长度为 n
时,GuessedName[n]
是超出范围的字符串下标 - 您无法访问结束后的一个元素 - 它不是空终止的。使用 for 循环:
for(int i = 0; i < GuessedName.length(); ++i)
cout << "?";
或者简单地说:
cout << std::string(GuessedName.length(), '?');
我需要有关非常基本的 C++ 代码的帮助。 我的程序是关于猜名游戏,我遇到的问题是通过 char
读取字符串 char#include <iostream>
#include <time.h>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
void Play(int, int,int, string[], string[]);
string GetRandomName(int, int, int , string[], string[]);
const int ArrayMax = 100;
void Play(int selection, int FArraySize, int MArraySize,string Female[], string Male[])
{
int MAX_TRIES = 3;
int i=0;
ofstream ofFile;
ifstream InFile;
int num_of_wrong_guesses=0;
char letter;
string GuessedName;
GuessedName = GetRandomName(selection, FArraySize, MArraySize, Female, Male);
cout << "Guess the following name:" << endl;
while (GuessedName[i]!= 0 ){
cout<<"?";
i++;
}
cout << "\nEnter a guess letter? or * to enter the entire name" << endl;
cin >> letter;
return;
}
我没有完成编码...
问题出在while循环中,不使用cstring如何解决? 你能帮帮我吗?
像这样更改 while 循环:
while (GuessedName[i]){
cout<<"?";
i++;
}
int i = 0;
while(GuessedName[i] != 0)
{
cout << "?";
i++;
}
似乎您正在尝试打印 ?
的序列以及要猜测的字符串长度。但是您不能将 std::string
视为 C 字符串。当其长度为 n
时,GuessedName[n]
是超出范围的字符串下标 - 您无法访问结束后的一个元素 - 它不是空终止的。使用 for 循环:
for(int i = 0; i < GuessedName.length(); ++i)
cout << "?";
或者简单地说:
cout << std::string(GuessedName.length(), '?');