1. 控制浮点数的输出格式 在C++中,可以使用 <iomanip>
头文件中提供的一些函数来控制浮点数的输出格式,主要包括setprecision()
, fixed
, scientific
等。
setprecision(int n)
:设置浮点数的精度,即显示的总位数或小数位数。
fixed
:以固定的小数点表示法显示浮点数。
scientific
:以科学计数法表示浮点数。
示例代码:
1 2 3 4 5 6 7 8 9 #include <iostream> #include <iomanip> int main () { double num = 3.141592653589793 ; std::cout << std::fixed << std::setprecision (2 ) << num << std::endl; std::cout << std::scientific << std::setprecision (3 ) << num << std::endl; return 0 ; }
2. 从文本文件和CSV文件中读取数据 读取文件通常使用 <fstream>
头文件中的 ifstream
类。
读取文本文件 :可以使用 ifstream
来打开文件,并使用 >>
操作符或 getline()
函数来读取数据。
读取CSV文件 :因为CSV文件中的数据通常由逗号分隔,所以可以使用 getline()
读取整行数据,然后使用 stringstream
来分离每个数据项。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> int main () { std::ifstream file ("data.csv" ) ; std::string line; while (getline (file, line)) { std::stringstream ss (line) ; std::string data; while (getline (ss, data, ',' )) { std::cout << data << std::endl; } } return 0 ; }
3. 将数据输出到文件 使用 <fstream>
头文件中的 ofstream
类来创建文件并写入数据。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <fstream> #include <iostream> int main () { std::ofstream outFile ("output.txt" ) ; double num = 3.14159 ; if (outFile.is_open ()) { outFile << "The value of pi is: " << num << std::endl; outFile.close (); } else { std::cout << "Unable to open file" ; } return 0 ; }
以上代码分别展示了如何控制浮点数输出格式、如何从文本和CSV文件读取数据,以及如何将数据输出到文件中。这些基本技能在处理C++文件和数据操作时非常重要。
4. 处理数据文件中的注释行 要读取一个以制表符和空格分隔的数据文件,并跳过前两行的注释,可以使用C++的标准库函数来实现。以下是一个示例函数,展示如何实现这一需求。
我们使用 std::ifstream
来读取文件,使用 std::istringstream
来分割字符串。数据将被存储到一个结构体的向量中,假设数据有两列,每列都是整数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> struct Data { int column1; int column2; };std::vector<Data> readData (const std::string& filename) { std::vector<Data> dataList; std::ifstream file (filename) ; std::string line; std::getline (file, line); std::getline (file, line); while (std::getline (file, line)) { std::istringstream iss (line) ; Data data; iss >> data.column1 >> data.column2; dataList.push_back (data); } file.close (); return dataList; }int main () { std::string filename = "input.txt" ; std::vector<Data> myData = readData (filename); for (const auto & data : myData) { std::cout << "Column 1: " << data.column1 << ", Column 2: " << data.column2 << std::endl; } return 0 ; }
说明
跳过注释 :使用 std::getline()
两次来读取并丢弃文件的前两行。
数据读取和分割 :之后对文件的每一行进行循环处理。每读取一行数据,就使用 std::istringstream
来分割这行数据。这里假设每行数据包含两个整数,它们可能由空格或制表符分开。
存储数据 :将分割后的数据存储到 Data
结构体的实例中,然后添加到 std::vector<Data>
的列表中。
这个函数可以灵活调整以适应不同格式的输入和不同的数据类型。如果数据列是其他类型(如 float
或 string
),你可以相应地修改 Data
结构体和读取数据的部分。
with the help of ChatGPT