Jcr*_*ack 1 c++ file-io fstream iostream
我习惯使用fscanf进行简单的文件输入,因为它使它变得简单.我试图转移到溪流,我希望能够做到这一点:
fscanf(file, %d %s, int1, str1);
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,通过一个文件读取相对容易,将第一个int粘贴到一个容器中,然后将第一个字符串粘贴到一个char*中.我想要的是使用流功能使用fstreams.这是我想出的,我有限的流知识.
while((fGet = File.get() != EOF))
{
int x;
int y;
bool oscillate = false;
switch(oscillate)
{
case false:
{
x = fGet;
oscillate = true;
break;
}
case true:
{
y = fGet;
oscillate = false;
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
基本上我想扫描一个文件并将第一个int放入x,第二个放入y.
正如你所知道的那样,这有几个原因非常糟糕,而且我从来没有真正使用它,但这是我能想到的全部.有没有更好的方法来解决这个问题?
要从流中读取两个整数,您所要做的就是
int x, y;
File >> x >> y;
Run Code Online (Sandbox Code Playgroud)
相当于
fscanf(file, "%d %s", &int1, str1);
Run Code Online (Sandbox Code Playgroud)
是
int x;
string s;
file >> x >> s;
Run Code Online (Sandbox Code Playgroud)
并确保如果要检查读取是否有效,请将读取条件放入:
if (file >> x >> s)
Run Code Online (Sandbox Code Playgroud)
要么
while (file >> x >> y)
Run Code Online (Sandbox Code Playgroud)
管他呢.
| 归档时间: |
|
| 查看次数: |
1102 次 |
| 最近记录: |