[英]In c++ how do I read from file x,y coordinates of a rectangle?
數據格式為:
0,0 2,0 2,4 0,4 (there are tabs in between each pair) 5,5 7,5 7,9 0,9
它們是文本文件的前兩行,每行代表一個三角形。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int x1, x2, x3, x4, y1, y2, y3, y4;
string coordinates;
ifstream myfile;
myfile.open("coordinates.txt");
string line = myfile.getline();
myfile>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4;
cout << line;
}
我嘗試了幾種方法將數據轉換為相關的整數,但沒有好運。 有人可以幫忙嗎?
您可以使用operator >>
:
myfile >> x1;
請注意,您應該包括<fstream>
。
我已經添加了
<fstream>
並使用了>>
運算符,但是我不知道如何處理制表符和逗號以及行之間的返回。
問題不在於制表符或換行符(因為流將它們視為空白,這些流在格式化I / O的哨兵操作中被提取並丟棄)。 問題在於逗號,因為它們沒有被提取。 這樣做,例如in >> x >> y
將離開y
如果有以前的萃取后的流中的非數字字符未初始化的x
。
您需要一種在第一次提取整數之后提取逗號的方法。 最簡單的技術是使用虛擬char
變量提取為:
int x1, y1;
char dummy;
if (myfile >> x1 >> dummy >> y1)
{
// ...
}
我只需要編寫一個簡短的程序,也許您可以使用其中的一些程序:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ifstream inFile;
float num1, num2, num3, num4, num5, sum, avg;
cout << "Reading data from the Z:CLM1.dat file:\n\n";
// Open the file.
inFile.open("Z:\\CLM1.dat");
// Read the five numbers from the file.
inFile >> num1;
inFile >> num2;
inFile >> num3;
inFile >> num4;
inFile >> num5;
// Close the file.
inFile.close();
// Calculate the sum of the numbers.
sum = num1 + num2 + num3 + num4 + num5;
avg = sum / 5;
// Display the five numbers.
cout << setprecision(3) << fixed << "Number 1 is " << num1 << "\n"
<< "Number 2 is " << num2 << "\n"
<< "Number 3 is " << num3 << "\n"
<< "Number 4 is " << num4 << "\n"
<< "Number 5 is " << num5 << "\n"
<< endl;
// Display the sum of the numbers.
cout << "The sum of the 5 numbers is: " << sum << endl;
cout << "The average of these 5 numbers is: " << avg << endl;
getchar();
return 0;
}
您說您想將數據讀取為單個整數,但您要將第一行的整個內容讀取為字符串,然后顯示它。
如果要從文本文件中讀取由空格字符(空格,制表符或換行符)分隔的整數,則只需要運算符>>:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
// Read in the entire file to a string
string fileContents;
ifstream fin;
fin.open("myfile.txt");
if(fin.is_open())
{
getline(fin,fileContents,'\x1A');
fin.close();
}
// Use the string to init an istringstream from which you can read
istringstream iss(fileContents);
// Read from the file contents
int x,y,z;
iss >> x;
iss >> y;
iss >> z;
// Display the integers
cout << x << ' ' << y << ' ' << z << '\n';
return 0;
}
請注意,我使用stringstream首先將文件的全部內容讀入內存,然后再從該流中讀取。 這是一個可選步驟,之所以這樣做,是因為我喜歡在對內容進行任何其他工作之前要盡快打開和關閉文件的習慣。 如果文件很大,這可能不是理想的。 可以對打開和關閉文件之間的花括號內的ifstream對象使用相同的運算符>>,並完全省略字符串流,如下所示:
int main()
{
int x,y,z;
// Open the file
ifstream fin;
fin.open("myfile.txt");
if(fin.is_open())
{
// Read from the file contents
fin >> x;
fin >> y;
fin >> z;
fin.close();
}
// Display the integers
cout << x << ' ' << y << ' ' << z << '\n';
return 0;
}
還要注意,沒有驗證可以確保您不會試圖讀取文件末尾之外的內容,所讀取的實際上是整數,僅讀取一定數量的整數等。對於那,我建議您首先閱讀一些簡單的輸入驗證教程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.