如果字符串是从字符类型中给定的,则该字符串是否可以包含换行符

Can a string hold a newline character if given from a char type?

本文关键字:字符串 是否 换行符 包含 字符 类型 如果      更新时间:2023-10-16

我的意思是。假设我们从标准输入中读取一堆文本,然后一个接一个地将其读取为字符类型。如果其中一个字符是换行符,那么这个变量显然可以保存关于换行符的信息。如果我将这个字符推送到字符串流中,然后将字符串流的内容输出到字符串中,该怎么办?

这个新字符串似乎没有包含任何关于换行符的数据。

有没有让字符串保存这些信息?

代码片段:

    stringstream ssChar;
    unsigned char aChar;
    string strChar;
    sourceFile >> noskipws >> aChar;
    ssChar << aChar;
    getline(ssChar, strChar);
    //ssChar.str("");
    //ssChar.seekg(0);
    cout << "Next char is: " << (int)aChar << endl;
    cout << "Length of char(from stringstream): " << strChar.length() << endl;

输入:带有换行符的文件xxd源文件

0000000:0a0a(实际上是2个换行符)。。

输出:下一个字符是:10(ascii换行符)字符长度:0(str为空)

答案是肯定的。当然,字符串会存储传递到其中的字符数据。代码中可能存在一些格式化操作,这些操作占用了空白或换行符。

为什么不测试它?

    > cat temp.cc
    #include<iostream>
using namespace std;
int main()
{
string str="vijayn";
cout << str <<"this is the next line"<<endl;
return 0;
}
    > ./a.out
    vijay
    this is the next line
    >