c++ - ifstream 其他行中的不同数据类型
问题描述
几周前我刚刚开始使用 C++,需要一些帮助来完成我的“作业”。
我需要阅读:
row1: int int
row2: int char
从文本文件。我的代码如下所示:
int main() {
[...]
ifstream fin(argv[1]);
int i{0}, tmp;
while (fin >> tmp) {
cout << pos << "zahl" << tmp << endl;
if (pos == 0) {
wagen = tmp;
} // needed for an array
if (pos == 1) {
reihen = tmp;
}
i++;
[...] return 0;
}
我的问题是你如何解决row2+
?我尝试了类型转换并在谷歌上搜索了一个多小时,但没有发现任何有用的东西。
解决方案
没有什么能阻止你拥有这样的结构。您只需在循环之外阅读:
int x, y;
std::cin >> x >> y;
int val;
char c;
while (!std::cin.eof()) /* while the end of the stream has
* not been reached yet */
{
int val;
std::cin >> val;
/* getting characters from a stream is tricky; consider a line such
* as "123 c\n"; you read the int, 123, but then when you read the
* character, you'll want the 'c', not a whitespace character, so
* "std::cin >> std::ws" consumes the "leading" whitespace before the
* character. */
char c = (std::cin >> std::ws).get();
/* next step is to ignore the trailing whitespace on the current line */
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
编辑:可能需要一些解释,所以我在代码注释中添加了它。
PS我自己没有测试过代码。
推荐阅读
- excel - 如何在excel中修剪或移动一列的最后一个字母到另一列。我附上了代码
- video - 如何在给定帧速率、分辨率和每像素颜色编码的情况下计算视频大小?
- c++ - 如何删除代码块中的环境错误
- excel - Excel VBA 副本创建新工作表而不是复制到现有工作表
- java - 字符串压缩到字符 ArrayList
- java - 如何在 Java 中将字符串转换为可运行代码
- reactjs - 如何更改material-ui Button的道具(变体)?
- css - 样式 css 文件未应用于我的网站,因为我猜是新的 Windows 更新
- apache-zookeeper - 无法启动 Zookeeper 收到异常说无法加载
- python - 为什么 SpeechRecognition 库不适用于临时音频文件?