[英]C++ read a file line by line but line type is CString or TCHAR
我得到以下示例
CString line[100];
//string line;
ifstream myfile (_T("example.txt"));
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
那条“行”是如何将值存储到类型 CString 或 TCHAR 的。 我收到这样的错误:
错误 C2664:'__thiscall std::basic_ifstream >::std::basic_ifstream >(const char *,int)'
请帮我 :)
首先,这个声明:
CString line[100];
定义了一个包含100 个CString
的数组:您确定要这样吗?
或者您可能只想要一个CString
来读取每一行?
// One line
CString line;
您可以选择将这些行读入std::string
,然后将结果转换为CString
:
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
// Convert from std::string to CString.
//
// Note that there is no CString constructor overload that takes
// a std::string directly; however, there are CString constructor
// overloads that take raw C-string pointers (e.g. const char*).
// So, it's possible to do the conversion requesting a raw const char*
// C-style string pointer from std::string, calling its c_str() method.
//
CString str(line.c_str());
cout << str.GetString() << '\n';
}
myfile.close();
}
std::getline()
的第二个参数需要一个std::string
,所以首先使用std::string
,然后将其转换为CString
string str_line;
ifstream myfile (_T("example.txt"));
if (myfile.is_open())
{
while ( getline (myfile, str_line) )
{
CString line(str_line.c_str());
cout << line << '\n';
}
myfile.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.