• A题笔记(2)


    No. 1505

    文件读相关

    #include <fstream>
    #include <sstream>

    <fstream>支持文件的IO

    <sstream>不加的话,若使用 istringstream 类型,会出现错误 error: variable ‘std::istringstream stream’ has initializer but incomplete type

        string file="1.txt";
        ifstream infile;
        infile.open(file.c_str(), fstream::in | fstream::out);

    以上代码可以用来打开一个文件,构造一个 ifstream 的读文件流,并同 file 绑定

    使用 open 打开或使用文件名作初始化,需要传递C风格字符串

    ifstream 的默认打开模式是 fstream::in

    若想检验文件是否打开了,可以使用 if(!infile) 但不知道为什么会报错......

        string line, word;
        while(getline(infile, line))
        {
            istringstream stream(line);
            while(stream >> word)
            {
             ////////////////////////////        
            }
        }
        

    以上代码可以用来从一个文件中每次取一个单词来进行处理

    getline()  从输入读取整行内容

    为了获得每行中的单词,将一个 istringstream 对象与所读取的行绑定起来,这样只需使用普通的 string 输入操作符杰克独处每行中的单词

       #include <cctype> 
      size_t index=0; for( index=0; index<word.size(); index++) { if(isalpha(word[index])) { //////////////// } }

    以上代码用来对 string 对象中的字符进行处理

    常用的函数有 isalnum()字母或数字 isalpha()字母 isdigit()数字 isspace()空白字符 ispunct()标点符号

        int i=atoi(word.c_str());
        double f=atof(word.c_str());

    以上代码可以用来将字符串转换成为 int 型或 double 型 数字

        int a;
        string str = "-1024";
        istringstream issInt(str);
        issInt >> a;

    使用c++中的字符串流 istringstream (c++) ,也可以将 string 型转换成 数字

  • 相关阅读:
    【Beta版本】冲刺-Day6
    【Beta版本】冲刺-Day5
    【Beta版本】冲刺-Day4
    【Beta版本】冲刺-Day3
    【Beta版本】冲刺-Day2
    【Beta版本】冲刺-Day1
    内存管理和虚拟内存
    C++11中的智能指针和锁的类型以及它们背后的RAII机制
    操作系统中面试时问到的相关知识点
    网络层(IP)相关知识
  • 原文地址:https://www.cnblogs.com/LeoGodfrey/p/3490292.html
Copyright © 2020-2023  润新知