我有一個字符串數組std::string words[4000]
充滿隨機單詞。我想檢查此數組中任何隨機單詞的大小。我想:C++如何檢查字符串數組內的元素的大小?
int x = words[rnd].length();
和
int x = words[rnd].size();
和
int x = sizeof(words[rnd]);
其中RND是()的返回蘭特一些。但是這兩次x的值都是0,sizeof()總是返回28.我在這裏做錯了什麼?
的人誰願意來檢查全碼:
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <stdlib.h>
std::string words[4000]; `
void fread(std::string fname, std::string words[], const int & nwords)
{
std::ifstream ifile(fname.c_str(), std::ios::in);
if (!ifile)
{
std::cout << " Couldn’t read the file " << fname;
exit(-1);
//return;
}
int count = 0;
while (ifile && count < nwords)
ifile >> words[count++];
ifile.close();
}
`int main()`
`{`
srand(time(NULL));
int nwords = 4000;
int rnd = rand() % nwords;
int x = words[rnd].length()/3;
fread("<location>", words, nwords);
int* hintloc = new int[x];
std::cout << words[rnd]; //this checks whether i have the right word
const int hangsize = 19;
bool chk;
std::cout << "\n\n\t\t\tGET READY FOR HANGMAN!\n\n\t\tGuess this word: ";
for (int i = 0; i < x; i++)
{
hintloc[i] = rand() % words[rnd].size();
for (int j = 0; j < i; j++)
{
if (hintloc[i] == hintloc[j])
i--;
}
}
for (int i = 0; i < words[rnd].size(); i++)
{
chk = true;
for (int j = 0; j < x; j++)
{
if (i == hintloc[j])
{
std::cout << words[rnd].at(i)<<" ";
chk = false;
}
}
if (chk == true)
std::cout << "_ ";
}
delete[] hintloc;
system("pause");
return 0;
}
你確定'rnd'是否在0..3999之內? – gurka
另外,sizeof(std :: string)'不會給你字符串的長度。它將返回'string'類/結構的大小,以字節爲單位。 – gurka
你如何初始化單詞? –