C++ 为什么Linux中的管道会丢失空间?

C++ 为什么Linux中的管道会丢失空间?,c++,pipe,C++,Pipe,我对Linux中的管道有一个问题。看起来空间字符在管道化后丢失。运行以下C++code #include <iostream> #include <stdio.h> #include <string.h> using namespace std; int main(){ char s[] = "ab cd", c; int n = strlen(s); for(int i = 0; i<n && (cin &g

我对Linux中的管道有一个问题。看起来空间字符在管道化后丢失。运行以下
C++
code

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int main(){
    char s[] = "ab cd", c;
    int n = strlen(s);
    for(int i = 0; i<n && (cin >> c); i++)
        if(s[i] != c){
            printf("wrong at %d : '%c' != '%c' \n", i, s[i], c);
            break;
        }
    return 0;
}
shell命令给出

wrong at 2 : ' ' != 'c'

这是正常的行为吗?如何避免在管道中丢失字符?

问题不在于管道,而在于跳过空白的c

如果您使用
cin>>noskipws>>c

或者像这样:

std::string q;
getline(cin, q);

for(i = 0; i < n && i < q.size(); i++)
{
  if (q[i] != s[i]) 
    ...
}
std::string q;
getline(cin,q);
对于(i=0;i
问题不在于管道,问题在于跳过空白的c

如果您使用
cin>>noskipws>>c

或者像这样:

std::string q;
getline(cin, q);

for(i = 0; i < n && i < q.size(); i++)
{
  if (q[i] != s[i]) 
    ...
}
std::string q;
getline(cin,q);
对于(i=0;i
这是使用
cin
时的默认行为,与管道无关

您可能希望告诉流不要忽略空白:

std::cin >> std::noskipws;

然后继续进行操作。

这是使用
cin
时的默认行为,与管道无关

您可能希望告诉流不要忽略空白:

std::cin >> std::noskipws;

然后继续你已经在做的事情。

因为CIN使用空格@kfsone-
cin
不使用空格;不管数据来自哪个流,流提取器(
operator>
)都会这样做。@PeteBecker是的,我的措辞很糟糕。因为CIN使用空格@kfsone-
cin
不使用空格;流提取器(
operator>
)执行此操作,而不管数据来自哪个流。@PeteBecker是的,我的措辞不好。这是使用流提取器(
operator>
)时的默认行为,而不管提取器应用于哪个流。除了使用
std::noskipws
,还可以使用
basic\u istream::get()
读取单个字符而不跳过空格<代码>运算符>>
是一种格式化的流操作
get
是未格式化的。这是使用流提取器(
operator>
)时的默认行为,无论提取器应用于哪个流。除了使用
std::noskipws
,还可以使用
basic\u istream::get()
读取单个字符而不跳过空格<代码>运算符>>是一种格式化的流操作<代码>获取未格式化。