PDA

View Full Version : QString assignment problem in C++ style but not in C style



timmu
29th December 2011, 14:49
Hi,

This C++ does not work:


string line;
getline (INfile,line);
QString Line = line;

error: conversion from ‘std::string’ to non-scalar type ‘QString’ requested

However this C style does work:


char line[50]="";
fgets(line, 50, INfile);
QString Line = line;


Why is that? I'd really like to get the C++ style to work. What's the best way to obtain a line from a file in Qt?

Thanks!!

stampede
29th December 2011, 15:05
Why is that?
Because there is no QString constructor taking a std::string as agrument.

What's the best way to obtain a line from a file in Qt?
Use QFile (http://doc.trolltech.com/main-snapshot/qfile.html) and QTextStream (http://developer.qt.nokia.com/doc/qt-4.8/qtextstream.html), there is an example of reading a file line-by-line in QFile documentation.

timmu
29th December 2011, 15:17
Thank you so much. But what would be the best way to read getline into QString then? How would I convert getline text into QString text?

Zlatomir
29th December 2011, 15:45
You can use the c_str() member function to get an char array from std::string.

stampede
29th December 2011, 15:47
Second example from QFile documentation:


QFile file("in.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;

QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine(); // here you have a line from text file stored in QString
}

timmu
29th December 2011, 16:37
Thanks all.

readLine() is a nice way to get the entire line into QString. But what if I want just one entry in a space-delimited file. I'd like to do what fsanf() does. What would be the analogous function to fscanf()?

Thanks!

amleto
29th December 2011, 19:37
using the operator >> from a std::ostream will probably suit your need.

e.g. for some fstream 'f', and some std::string 'str':

f >> str;

although you can get some empty tokens from end of lines etc.