Декларация
char *words[9];
объявляет необработанный массив указателей. Этот массив не инициализирован, поэтому указатели имеют неопределенные значения. Использование любого из них будет неопределенным поведением.
Вместо этого вы хотите
vector<string> words;
где vector
— это std::vector
из заголовка <vector>
, а string
— это std::string
из заголовка <string>
.
Используйте функцию-член push_back
, чтобы добавить строки в конец вектора.
Также вам нужно переместить вызов close
из цикла. В противном случае он закроет файл в первой итерации.
Этот подход дает код (неожиданно, отказ от ответственности...)
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> words;
ifstream inStream;
inStream.open("sentence.txt");
for ( int i = 0; i < 10; i++)
{
string word;
if( inStream >> word )
words.push_back( word );
}
inStream.close();
}
Если вы не можете использовать std::string
и std::vector
, вам нужно инициализировать массив указателей и убедиться, что вы не читаете в буферы больше, чем есть место.
Основная проблема здесь в том, что >>
небезопасно для чтения в необработанный массив, заданный указателем. Он не знает, насколько велик этот массив. Это может легко привести к переполнению буфера с ужасными последствиями.
Итак, это становится немного сложным, но это может выглядеть так:
#include <ctype.h> // isspace
#include <fstream>
#include <iostream>
#include <locale.h> // setlocale, LC_ALL
#include <stdlib.h> // EXIT_FAILURE
using namespace std;
void fail( char const* const message )
{
cerr << "! " << message << "\n";
exit( EXIT_FAILURE );
}
void readWordFrom( istream& stream, char* const p_buffer, int const buffer_size )
{
int charCode;
// Skip whitespace:
while( (charCode = stream.get()) != EOF and isspace( charCode ) ) {}
int n_read = 0;
char* p = p_buffer;
while( n_read < buffer_size - 1 and charCode != EOF and not isspace( charCode ) )
{
*p = charCode; ++p;
++n_read;
charCode = stream.get();
}
*p = '\0'; // Terminating null-byte.
if( charCode != EOF )
{
stream.putback( charCode );
if( not isspace( charCode ) )
{
assert( n_read == buffer_size - 1 ); // We exceeded buffer size.
stream.setstate( ios::failbit );
}
}
}
int main()
{
static int const n_words = 9;
static int const max_word_length = 80;
static int const buffer_size = max_word_length + 1; // For end byte.
char *words[n_words];
for( auto& p_word : words ) { p_word = new char[buffer_size]; }
ifstream inStream{ "sentence.txt" };
if( inStream.fail() ) { fail( "Input file opening failed." ); }
setlocale( LC_ALL, "" ); // Pedantically necessary for `isspace`.
for( auto const p_word : words )
{
readWordFrom( inStream, p_word, buffer_size );
if( inStream.fail() ) { fail( "Reading a word failed." ); }
}
for( auto const p_word : words ) { cout << p_word << "\n"; }
for( auto const p_word : words ) { delete[] p_word; }
}
person
Cheers and hth. - Alf
schedule
09.02.2017
std::string
? - person Ed Heal   schedule 09.02.2017std::ifstream inStream("sentence.txt");
. И не утруждайте себя его закрытием; когдаinStream
выходит из области видимости, его деструктор закроет его. - person Pete Becker   schedule 09.02.2017__
? - person Ed Heal   schedule 09.02.2017