c++读取txt文件,每行两个数据,按空格分开读取
时间: 2024-05-05 19:17:52 浏览: 13
好的,这是一个技术问题,我很乐意回答。你可以使用以下代码读取txt文件中每行的两个数据并按空格分开:
```
#include <stdio.h>
int main() {
FILE *fp;
char filename[] = "data.txt";
char word1[10], word2[10];
fp = fopen(filename, "r");
if (fp == NULL) {
printf("无法打开文件 %s", filename);
return 0;
}
while (fscanf(fp, "%s %s", word1, word2) != EOF) {
printf("%s %s\n", word1, word2);
}
fclose(fp);
return 0;
}
```
其中,filename 是你要读取的txt文件名,word1和word2是每行中的两个数据。这份代码将每行的两个数据打印出来。希望对你有所帮助。
相关问题
c++读取txt文件中的每行数据
在C++中,可以使用标准库中的fstream类读取文本文件。以下是一个使用fstream类读取txt文件中每行数据的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::ifstream infile("example.txt"); // 打开文本文件
if(infile){
std::string line;
while(std::getline(infile, line)){ // 逐行读取文件内容
std::cout << line << std::endl; // 输出每行数据
}
}
infile.close(); // 关闭文本文件
return 0;
}
```
以上示例代码假设txt文件名为example.txt,每行数据以换行符分隔。你可以根据实际情况修改代码中的对应参数。
c++读取txt文件数据
以下是使用C++读取txt文件数据的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt"); // 打开文件
std::string line;
if (file.is_open()) {
while (getline(file, line)) { // 逐行读取文件内容
std::cout << line << std::endl; // 输出每行内容
}
file.close(); // 关闭文件
} else {
std::cout << "无法打开文件" << std::endl;
}
return 0;
}
```
这段代码首先使用`ifstream`类打开名为"example.txt"的文件。然后,使用`getline`函数逐行读取文件内容,并将每行内容存储在`line`字符串中。最后,通过`cout`语句将每行内容输出到控制台。如果无法打开文件,则会输出"无法打开文件"。