[英]Reading integers and strings from a text file and storing in parallel arrays
[英]Reading and storing integers in a file
我有一個file.txt,例如:
15 25 32 // exactly 3 integers in the first line.
string1
string2
string3
*
*
*
*
我想做的是,閱讀15,25,32並將其存儲為int a,b,c;
有沒有人可以幫助我? 提前致謝。
標准習慣用法使用iostream:
#include <fstream>
#include <sstream>
#include <string>
std::ifstream infile("thefile.txt");
std::string first_line;
if (!infile || !std::getline(first_line, infile)) { /* bad file, die */ }
std::istringstream iss(first_line);
int a, b, c;
if (!(iss >> a >> b >> c >> std::ws) || iss.get() != EOF)
{
// bad first line, die
}
// use a, b, c
您可以使用std::ifstream
讀取文件內容:
#include <fstream>
std::ifstream infile("filename.txt");
然后,您可以使用std::getline()
讀取帶有數字的行:
#include <sstream>
#include <string>
std::string line;
std::getline(infile, line);
然后,您可以使用std::istringstream
解析存儲在該行中的整數:
std::istringstream iss(line);
int a;
int b;
int c;
iss >> a >> b >> c;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.