从外部文件获取输入

从外部文件获取输入

本文介绍了从外部文件获取输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从C ++中的外部文件获得非常基本的输入。我试图搜索互联网几次,但没有什么真正应用到我所需要的。这将是一个.txt文件,它的输入来自它,它将用如下行填充:

I need to get very basic input from an external file in C++. I tried searching the internet a few times but nothing really applied to what I need. This would be a .txt file that the input it coming from, and it would be filled with lines like this:

131

241

371

481

131
241
371
481

我有代码已手动获取此输入,它如下所示:

I have code already to manually get this input, and it looks like this:

using namespace std;
//Gets the initial values from the user.
    int control=0;
    while (rowb!=0){
        cout << "Row: ";
        cin >> rowb;
        cout << "Column: ";
        cin >> columnb;
        cout << "Number: ";
        cin >> numb;
        row[control]=rowb-1;
        column[control]=columnb-1;
        num[control]=numb;
        control++;
    }

这是解决sudoko主板的程序的一部分。输入的数字是sudoko板保存的初始值,用户输入来自板的行,列和数字。

我需要的是能够创建.txt文件,这些数字存储在行,使我不必输入这么多的数字。我不知道如何去做这个。主要是我将只使用txt文件来测试我的程序,我随着添加更多的代码。在我的程序中需要150多个输入的数字,只是为了得到一个单板,它需要很多时间。任何意外错误输入值也是一个巨大的问题,因为我不得不重新开始。那么我如何让C ++读取一个文本文件并使用这些数字作为输入?

This is part of a program that solves sudoko boards. The inputed numbers are the initial values that a sudoko board holds, and the user is inputing the row, column, and number that comes from a board.
What I need is to be able to create a .txt file with these numbers stored in rows so that I do not have to enter so many numbers. I have very little idea how to go about doing this. Mainly I'll only be using the txt file for testing my program as I move along with adding more code to it. It takes 150+ entered numbers within my program just to get a single board, and it takes a lot of time. Any accidentally wrong entered value is also a huge problem as I have to start again. So how would I get C++ to read a text file and use those numbers as input?

推荐答案

从头< fstream> 中的 std :: ifstream ,然后从中读取, $ c> std :: cin 。

You can open a file for input with std::ifstream from the header <fstream>, then read from it as you would from std::cin.

int main()
{
    std::ifstream input("somefile.txt");
    int a;
    input >> a;  // reads a number from somefile.txt
}

显然,您可以使用>> 在循环中读取多个数字。

Obviously, you can use >> in a loop to read multiple numbers.

这篇关于从外部文件获取输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 15:54