c++ getline

一、基本介绍

c++ getline是一种用于从输入流中获取一行文本的函数。它具有灵活、易用的特点,可以支持多种输入流类型,包括标准输入、文件以及字符串等。该函数可以帮助程序员处理各种数据格式的输入,是c++输入输出中一个使用频率非常高的函数。

二、函数原型与参数

c++ getline函数的原型如下:

istream& getline (istream& is, string& str, char delim);

其中,istream表示输入流类型,string表示存储输入文本的字符串变量,delim表示文本分隔符,通常为换行符,也可以自定义其他分隔符。

三、使用示例

1. 从标准输入中读取一行文本

#include 
#include 

using namespace std;

int main()
{
    string line;
    getline(cin, line);
    cout << "输入的内容为:" << line << endl;
    return 0;
}

运行程序后,程序会等待用户输入一行文本,然后把文本存放进line变量中,并输出到控制台上。

2. 从文件中读取多行文本

#include 
#include 
#include 

using namespace std;

int main()
{
    ifstream file("data.txt");
    if (!file.is_open())
    {
        cout << "文件打开失败!" << endl;
        return 1;
    }

    string line;
    while(getline(file, line))
    {
        cout << line << endl;
    }

    file.close();
    return 0;
}

该程序使用ifstream类型打开data.txt文件,并通过getline函数逐行读取文件内容,并输出到控制台上。

3. 使用分隔符获取单词

#include 
#include 
#include 

using namespace std;

vector split(string str, char delim)
{
    vector result;
    string word;
    stringstream ss(str);
    while (getline(ss, word, delim))
    {
        result.push_back(word);
    }
    return result;
}

int main()
{
    string sentence = "hello,world,i,am,your,friend!";
    vector words = split(sentence, ',');

    cout << "分隔后的单词为:" << endl;
    for (auto word : words)
    {
        cout << word << endl;
    }

    return 0;
}

该程序使用自定义分隔符逐个获取单词,通过调用split函数,并将单词存储在vector容器中,最后输出到控制台上。

四、常见问题

1. 如何避免读取空行?

可以使用getline函数后判断读取的内容是否为空,如果为空,则说明读取到了空行,可以使用continue语句继续读取下一行。

string line;
while (getline(file, line))
{
    if (line.empty()) continue;
}

2. 如何使用getline函数读取空格?

getline函数默认以换行符为分隔符,如果需要读取包含空格的文本,可以设置分隔符为空格:

string str;
getline(cin, str, ' ');

这样,就可以读取到包含空格的文本字符串。

3. 如何更改getline函数的默认分隔符?

可以使用istream类的成员函数getline(char*, streamsize, char)来更改默认分隔符。例如,下面的示例将把’\n’替换为’;’符号:

#include 
#include 
using namespace std;

int main(void)
{
      char str[] = "A;B;C\nD;E;F\nG;H;I";
      char *token;

      token = strtok(str, ";");
      while (token != NULL) {
            cout << token << endl;
            token = strtok(NULL, ";");
      }

      return 0;
}

在该程序中,先使用c函数strtok将str分割为token,其分隔符为分号’;’,然后从中筛选需要的信息。

原创文章,作者:OZHM,如若转载,请注明出处:https://www.506064.com/n/142929.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
OZHMOZHM
上一篇 2024-10-14 18:43
下一篇 2024-10-14 18:43

相关推荐

  • C++ getline函数详解

    一、getline函数的概述 getline函数是流输入输出库中的一个函数,其主要作用是从指定的流中读取一行字符,将其存放到一个字符串变量中,并返回流对象,以便可以使用流对象进行更…

    编程 2025-04-12
  • 详解getline头文件

    一、fgets头文件 fgets头文件是一个经典的C语言输入输出函数,其定义如下: #include <stdio.h> char *fgets(char *str, …

    编程 2024-12-01

发表回复

登录后才能评论