He creado un archivo de texto love.txt
:
i love you you love me
¿Cómo los line1
en una matriz separada, concretamente line1
y line1
y luego los line1
en la consola?
#include #include #include using namespace std; int main() { string line1[30]; string line2[30]; ifstream myfile("love.txt"); int a = 0; int b = 0; if(!myfile) { cout<<"Error opening output file"<<endl; system("pause"); return -1; } while(!myfile.eof()) { getline(myfile,line1[a],' '); cout<<"1."<<line1[a]<<"\n"; getline(myfile,line2[b],' '); cout<<"2."<<line2[b]<<"\n"; } }
Intente especificar el último argumento como ‘\ n’ en ambas funciones getline()
:
getline(myfile, line1[a], '\n');
en lugar de
getline(myfile, line1[a], ' ');
Puede pensar en una cadena como una matriz de caracteres, por lo que solo necesitará una matriz de cadenas:
const size_t SIZE = 30; string line[SIZE]; // creates SIZE empty strings size_t i=0; while(!myfile.eof() && i < SIZE) { getline(myfile,line[i]); // read the next line into the next string ++i; } for (i=0; i < SIZE; ++i) { if (!line[i].empty()) { // print only if there is something in the current line cout << i << ". " << line[i]; } }
Puede mantener un contador para ver también cuántas líneas ha almacenado (en lugar de buscar líneas vacías). De esta manera, también imprimirá correctamente las líneas vacías:
const size_t SIZE = 30; string line[SIZE]; // creates SIZE empty strings size_t i=0; while(!myfile.eof() && i < SIZE) { getline(myfile,line[i]); // read the next line into the next string ++i; } size_t numLines = i; for (i=0; i < numLines; ++i) { cout << i << ". " << line[i]; // no need to test for empty lines any more }
Nota : solo podrá almacenar hasta SIZE
líneas. Si necesita más, deberá boost el SIZE
en el código. Más adelante, aprenderá acerca de std::vector<>
que le permite boost el tamaño de forma dinámica según sea necesario (por lo que no necesitará realizar un seguimiento de la cantidad que almacenó).
Nota : el uso de constantes como SIZE
permite cambiar el tamaño en un solo lugar
Nota : debe agregar una verificación de errores en el flujo de entrada en la parte superior de eof()
: en caso de que haya un error de lectura que no sea el final del archivo:
while (myfile && ...) { // ... }
aquí myfile
se convierte a un valor booleano que indica si está bien usarlo ( true
) o no ( false
)
Actualización :
Acabo de darme cuenta de lo que está buscando: desea leer la entrada como una serie de palabras (separadas por espacios), pero mostrarlas como líneas. En este caso, necesitará arrays-of-arrays para almacenar cada línea.
string line[SIZE1][SIZE2];
donde SIZE1
es la cantidad máxima de líneas que puede almacenar y SIZE2
es la cantidad máxima de palabras que puede almacenar por línea
El relleno de esta matriz será más complejo: deberá leer la entrada línea por línea y luego separar las palabras dentro de la línea:
string tmp; // temporary string to store the line-as-string getline(myfile, tmp); stringstream ss(tmp); // convert the line to an input stream to be able to extract // the words size_t j=0; // the current word index while (ss) { ss >> line[i][j]; // here i is as above: the current line index ++j; }
Salida:
for (i=0; i < numLines; ++i) { cout << i << ". "; for (size_t j=0; j < SIZE2; ++j) { if (!line[i][j].empty()) { cout << line[i][j] << " "; } } }
Qué tal esto.. .
vector v; string line; ifstream fin("love.txt"); while(getline(fin,line)){ v.push_back(line); }