Fichas de arquivo ++ Leitura C
Pergunta
outro pedido desculpe .. Agora eu estou lendo as fichas em um por um e ele funciona, mas eu quero saber quando há uma nova linha ..
Se meu arquivo contém
Hey Bob
Now
deve me
darHey
Bob
[NEW LINE]
NOW
Existe uma maneira de fazer isso sem usar getline?
Solução
Sim, o operador >> quando usado com corda ler 'espaço branco' palavras separadas. A 'White espaço' inclui guia espaço e caracteres de nova linha.
Se você quiser ler uma linha em um tempo de uso std :: getline ()
A linha pode então ser indexado separadamente com um fluxo de string.
std::string line;
while(std::getline(std::cin,line))
{
// If you then want to tokenize the line use a string stream:
std::stringstream lineStream(line);
std::string token;
while(lineStream >> token)
{
std::cout << "Token(" << token << ")\n";
}
std::cout << "New Line Detected\n";
}
Além pequeno:
Sem usar getline ()
Então, você realmente quer ser capaz de detectar uma nova linha. Isto significa que nova linha torna-se um outro tipo de token. Então vamos supor que você tem palavras separadas por 'espaços brancos' como tokens e de nova linha como o seu próprio token.
Em seguida, você pode criar um tipo de token.
Então tudo que você tem a fazer é escrever os operadores de fluxo para um token:
#include <iostream>
#include <fstream>
class Token
{
private:
friend std::ostream& operator<<(std::ostream&,Token const&);
friend std::istream& operator>>(std::istream&,Token&);
std::string value;
};
std::istream& operator>>(std::istream& str,Token& data)
{
// Check to make sure the stream is OK.
if (!str)
{ return str;
}
char x;
// Drop leading space
do
{
x = str.get();
}
while(str && isspace(x) && (x != '\n'));
// If the stream is done. exit now.
if (!str)
{
return str;
}
// We have skipped all white space up to the
// start of the first token. We can now modify data.
data.value ="";
// If the token is a '\n' We are finished.
if (x == '\n')
{ data.value = "\n";
return str;
}
// Otherwise read the next token in.
str.unget();
str >> data.value;
return str;
}
std::ostream& operator<<(std::ostream& str,Token const& data)
{
return str << data.value;
}
int main()
{
std::ifstream f("PLOP");
Token x;
while(f >> x)
{
std::cout << "Token(" << x << ")\n";
}
}
Outras dicas
Eu não sei por que você acha std::getline
é ruim. Você pode ainda reconhecer novas linhas.
std::string token;
std::ifstream file("file.txt");
while(std::getline(file, token)) {
std::istringstream line(token);
while(line >> token) {
std::cout << "Token :" << token << std::endl;
}
if(file.unget().get() == '\n') {
std::cout << "newline found" << std::endl;
}
}
Este é um outro fresco e muito menos detalhado maneira que eu me deparei com cordas tokenizar.
vector<string> vec; //we'll put all of the tokens in here
string token;
istringstream iss("put text here");
while ( getline(iss, token, '\n') ) {
vec.push_back(token);
}