简体   繁体   English

在C ++中,我如何从文件的x,y坐标中读取矩形?

[英]In c++ how do I read from file x,y coordinates of a rectangle?

The data is in the form: 数据格式为:

 0,0 2,0 2,4 0,4 (there are tabs in between each pair) 5,5 7,5 7,9 0,9 

where they are the first two lines of the text file, each representing a triangle. 它们是文本文件的前两行,每行代表一个三角形。

#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;
}

I tried several ways to get the data into the relevant integers but with no luck. 我尝试了几种方法将数据转换为相关的整数,但没有好运。 Can someone please help? 有人可以帮忙吗?

C++'s stream input mechanisms are, quite frankly, incredibly annoying to use. 坦率地说,C ++的流输入机制令人讨厌。 If you're able to use a very recent version of C++, you might consider using regular expressions. 如果您能够使用最新版本的C ++,则可以考虑使用正则表达式。 Fetch the line from the stream using getline and then using a regex expression on each line.. something like ^(?:(\\d+),(\\d+)\\t){3}(\\d+),(\\d+)$ . 使用getline从流中获取行,然后在每行上使用正则表达式。.类似^(?:(\\d+),(\\d+)\\t){3}(\\d+),(\\d+)$

Failing that, sscanf can also be used, and while it's not as C++ as you might want, it's much easier to understand than the corresponding stream operations IMO. 失败的话,也可以使用sscanf,尽管它不像您想要的那样C ++,但是比相应的IMO操作流更容易理解。

You could use operator >> : 您可以使用operator >>

myfile >> x1;

Note that you should include <fstream> . 请注意,您应该包括<fstream>

I already added <fstream> and used the >> operator, however I don't know how to deal with the tabs and the commas and the return in between lines. 我已经添加了<fstream>并使用了>>运算符,但是我不知道如何处理制表符和逗号以及行之间的返回。

The problem is not with the tabs or the newline (because they are considered whitespace by the stream which are extracted and discarded as part of a sentry operation to formatted I/O). 问题不在于制表符或换行符(因为流将它们视为空白,这些流在格式化I / O的哨兵操作中被提取并丢弃)。 The problem is with the commas, because they are not extracted. 问题在于逗号,因为它们没有被提取。 Doing, for example in >> x >> y will leave y uninitialized if there is a non-numeric character in the stream after the previous extraction to x . 这样做,例如in >> x >> y将离开y如果有以前的萃取后的流中的非数字字符未初始化的x

You need a way to extract the comma after the first extraction of the integer. 您需要一种在第一次提取整数之后提取逗号的方法。 The most simple technique would be to use a dummy char variable to extract into: 最简单的技术是使用虚拟char变量提取为:

int x1, y1;
char dummy;

if (myfile >> x1 >> dummy >> y1)
{
    // ...
}

Just a short program I had to write maybe you can use some of it: 我只需要编写一个简短的程序,也许您可​​以使用其中的一些程序:

#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;
} 

You say you want to read data into individual integers, but you're reading the entire first line into a string and then displaying it. 您说您想将数据读取为单个整数,但您要将第一行的整个内容读取为字符串,然后显示它。

If you want to read integers from a text file, which are separated by whitespace characters (spaces, tabs, or newlines), then the operator >> is all you need: 如果要从文本文件中读取由空格字符(空格,制表符或换行符)分隔的整数,则只需要运算符>>:

#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;
}

Note that I use a stringstream to read the entire contents of the file into memory first, and then read from that stream. 请注意,我使用stringstream首先将文件的全部内容读入内存,然后再从该流中读取。 That is an optional step, which I do simply because I prefer the habit of opening and closing the file as quickly as possible before doing any additional work on the contents. 这是一个可选步骤,之所以这样做,是因为我喜欢在对内容进行任何其他工作之前要尽快打开和关闭文件的习惯。 This might not be ideal if the file is extremely large. 如果文件很大,这可能不是理想的。 You can use the same operator >> with the ifstream object inside the braces between where you open and close the file, and leave out the stringstream entirely, as demonstrated below: 可以对打开和关闭文件之间的花括号内的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;
}

Also note that there is no validation to ensure that you're not trying to read past the end of the file, that what you're reading are in fact integers, that you're only reading a certain number of them, etc. For that, I would advise that you first read up on some simple input validation tutorials. 还要注意,没有验证可以确保您不会试图读取文件末尾之外的内容,所读取的实际上是整数,仅读取一定数量的整数等。对于那,我建议您首先阅读一些简单的输入验证教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM