C++输入和输出

566 阅读1分钟

C++输入和输出

C++输入和输出可以通过iostream头文件中的cin和cout对象实现。

常用的输入方式有两种:使用cin对象和使用scanf函数。

使用cin对象时需要使用>>运算符,读入的数据可以是整型、浮点型、字符型、字符串等类型。

使用scanf函数的用法与C语言中相同,需要先指定格式化字符串,再将读入的数据存储到对应的变量中。与cin不同的是,scanf函数使用&符号获取变量地址。

常用的输出方式有两种:使用cout和printf函数。

使用cout对象输出数据时,需要使用<<运算符。输出的数据可以是整型、浮点型、字符型、字符串等类型。

使用printf函数的用法与C语言中相同,同样需要指定格式化字符串。

在输出字符串时,可以使用string对象或C风格的字符串。

C++中输入和输出分别通过iostream头文件中的cin和cout对象实现。

输入

C++中常用的输入方式有两种:使用cin对象和使用scanf函数。其中,cin方式更为直观、简单。

使用cin

使用cin对象时需要使用>>运算符,读入的数据可以是整型、浮点型、字符型、字符串等类型。

以读取一个整型为例:

#include <iostream>
using namespace std;

int main() {
    int num;
    cin >> num;
    cout << "You input: " << num << endl;
    return 0;
}

Copy

输出:

23
You input: 23

同样地,可以读入浮点型、字符型等类型的数据。

使用scanf

scanf函数的用法与C语言中相同,需要先指定格式化字符串,再将读入的数据存储到对应的变量中。与cin不同的是,scanf函数使用&符号获取变量地址。

以读取两个整型为例:

#include <stdio.h>

int main() {
    int num1, num2;
    scanf("%d %d", &num1, &num2);
    printf("You input: %d %d", num1, num2);
    return 0;
}

输出:

23 45
You input: 23 45

输入字符串

为防止cin读入字符串时截断,建议使用getline函数。该函数读入一行字符串并存储到string对象中。

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

int main() {
    string str;
    getline(cin, str);
    cout << "You input: " << str << endl;
    return 0;
}

输出:

Hello, world!
You input: Hello, world!

输出

输出的方式与输入类似,同样有cout和printf函数两种方式。

使用cout

使用cout对象输出数据时,需要使用<<运算符。输出的数据可以是整型、浮点型、字符型、字符串等类型。

#include <iostream>
using namespace std;

int main() {
    int num = 23;
    cout << "You output: " << num << endl;
    return 0;
}

输出:

You output: 23

使用printf

printf函数的用法与C语言中相同,同样需要指定格式化字符串。

#include <stdio.h>

int main() {
    int num = 23;
    printf("You output: %d", num);
    return 0;
}

输出:

You output: 23

输出字符串

使用cout对象输出字符串时,可以直接输出string对象或C风格的字符串。

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

int main() {
    string str = "Hello, world!";
    cout << "You output: " << str << endl;

    char c_str[] = "Hello, world!";
    cout << "You output: " << c_str << endl;
    return 0;
}

输出:

You output: Hello, world!
You output: Hello, world!

以上就是C++输入输出的基本知识。