C++如何从文件中设置字符串变量
C++ How to set a string variable from a file?
我想知道如何在程序中读取WHOLE txt文件并将其内容设置为1个字符串。我已经声明了我的字符串:
const string SLOWA[ILOSC_WYRAZOW][ILOSC_POL] =
{
{"kalkulator", "Liczysz na tym."},
{"monitor", "pokazuje obraz."},
{"kupa", "robisz to w toalecie"}
};
我不想把它放在程序中,而是想把这个字符串的内部放在.txt文件中,读取整个内容并将其设置为我的字符串。有可能吗?
试试这个:
#include<iostream>
#include<fstream.h>
using namespace std;
int main(){
ifstream file("d:\data.txt");
string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
cout<<content;
getchar();
return 0;
}
现在content
变量包含文件中的全部数据。
文件data.txt
包含:
this is file handling
and this is contents.
输出:
this is file handling
and this is contents.
以下内容将起作用:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string line;
string mystring;
ifstream myfile ("example.txt"); // Need to be in the directory where this program resides.
if (myfile.is_open())
{
while ( getline (myfile,line) ) // Get one line at a time.
{
mystring += line + 'n'; // 'n' at the end because streams read line by line
}
myfile.close(); //Close the file
}
else
cout << "Unable to open file";
cout<<mystring<<endl;
return 0;
}
但看看流是如何工作的:
http://courses.cs.vt.edu/cs1044/Notes/C04.IO.pdf
http://www.cplusplus.com/reference/iolibrary/
相关文章:
- C++ 命名参数习惯用语 - 未设置字符串属性
- 如何将字符串属性设置为 QTreeWidgetItem?
- 我如何处理有关输入的字符串大小超过字符数组设置大小的错误?
- C++如何将字符串数组中的一个点设置为枚举变量
- 从C++为字符串函数设置_ENV
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 通过比较字符设置字符串时出现问题
- 如何在 c++ 中从字符串向量设置类对象
- STD ::设置带有字符串键和潜在效率损失
- 如何调用 GetAltMonthNames 来填充外部区域设置月份字符串的安全数组
- 设置可变值通过字符串引用它
- 仅使用 getName 在主函数中设置字符串名称
- 用设置功能在类中设置字符串
- 如何从十六进制设置字符串值
- 为什么这段代码跳过设置字符串变量的 if 语句
- 使用C/C++设置字符串格式
- C++如何从文件中设置字符串变量
- 设置字符串为v8 Array
- 通过指针在结构中设置字符串时发生C++错误
- 如何在c++类中设置c字符串的默认值