📜  C++中的基本输入输出(1)

📅  最后修改于: 2023-12-03 15:14:03.481000             🧑  作者: Mango

C++中的基本输入输出

在C++中,输入和输出是非常重要和基本的操作。C++提供了一组标准的输入和输出工具,可以帮助我们方便地从程序中获取输入和输出结果。

输出

在C++中,输出是使用标准输出流cout实现的。我们可以使用<<运算符将要输出的内容插入到输出流中。例如:

#include<iostream>
using namespace std;

int main()
{
    cout<<"Hello World!";
    return 0;
}

输出结果为:

Hello World!

上面的代码演示了如何在控制台中输出一条简单的信息。

除了输出字符串以外,我们还可以输出变量的值。例如:

#include<iostream>
using namespace std;

int main()
{
    int age = 18;
    cout<<"My age is: "<<age;
    return 0;
}

输出结果为:

My age is: 18
输入

在C++中,输入是使用标准输入流cin实现的。我们可以使用>>运算符将输入插入到流中。例如:

#include<iostream>
using namespace std;

int main()
{
    int age;
    cout<<"Please enter your age: ";
    cin>>age;
    cout<<"Your age is: "<<age;
    return 0;
}

输出结果为:

Please enter your age: 18
Your age is: 18

上面的代码演示了如何从控制台中获取用户输入的数据。

格式化输出

在输出时,我们可以使用setw()函数来设置输出的宽度,并使用leftrightinternal等标志来控制输出内容的对齐方式。例如:

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
    cout<<setw(10)<<setfill('*')<<left<<"Hello"<<endl;
    cout<<setw(10)<<setfill('*')<<right<<"World"<<endl;
    cout<<setw(10)<<setfill('*')<<internal<<"C++"<<endl;
    return 0;
}

输出结果为:

Hello*****
*****World
*****C++ 

上面的代码演示了如何格式化输出内容,可以通过设置宽度和填充字符来实现对齐。使用internal标志可以使得填充字符在输出内容的前后交替出现。

文件输入输出

除了控制台输入输出外,C++还支持文件输入输出。使用文件输入输出需要包含头文件<fstream>。其中,文件输入流ifstream用于读取文件中的内容,文件输出流ofstream用于向文件中写入内容。例如:

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
    ofstream fout("output.txt", ios::out);
    fout<<"Hello World!";
    fout.close();

    ifstream fin("output.txt");
    string line;
    getline(fin, line);
    cout<<line;
    fin.close();

    return 0;
}

输出结果为:

Hello World!

上面的代码演示了如何使用文件输入输出来读取和写入文件。在这个例子中,我们创建了一个名为output.txt的文件,并向其中写入了Hello World!这个字符串。接着,使用文件输入流ifstream从文件中读取内容,并输出到控制台中。注意,在使用文件输入输出时,需要手动关闭输出流和输入流。