小编Enz*_*ura的帖子

C++ - 为什么 fflush(stdout) 不能与 iostream 一起使用?

我正在阅读freopen()并意识到,如果我们为其指定 stdin/stdout,即使我们使用 cin/cout 进行编码,该函数也将起作用。

研究了一下,我发现这个链接 freopen() 相当于 c++streams,其中一位用户回答:

来自 C++ 标准 27.3.1:
“该对象cin控制来自与该对象关联的流缓冲区的输入stdin,在 中声明<cstdio>。”

所以根据标准,如果我们重定向stdin它也会重定向cin。反之亦然cout

在 CPPReference 上也看到了类似的内容:
http://en.cppreference.com/w/cpp/io/cin
http://en.cppreference.com/w/cpp/io/cout

全局对象 std::cout 和 std::wcout 控制输出到实现定义类型(派生自 std::streambuf)的流缓冲区,与标准 C 输出流 stdout 关联。

这就是有点令人困惑的地方,因为我也在阅读有关刷新的内容,并注意到 fflush(stdout) 根本无法与 cin/cout 一起使用。

例如,此示例代码不会打印任何内容:

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;
    cout << "Please, enter a number: \n";
    fflush(stdout);
    cin >> n;
}
Run Code Online (Sandbox Code Playgroud)

下面的代码将打印到output.txt:

#include <cstdio> …
Run Code Online (Sandbox Code Playgroud)

c++ iostream stdio fflush

2
推荐指数
1
解决办法
4584
查看次数

C - 程序为SEGFAULT提供了for循环,但并非没有

我正在做一个读取3x3矩阵的程序.

#include <stdio.h>
#include <stdlib.h>

typedef struct { 
    int row;
    int col;
    long **tab;
} matr;

int SIZE = 3;

void *emalloc(size_t size) {
    void *memory = malloc(size);

    if (!memory) {
        fprintf(stderr, "ERROR: Failed to malloc.\n");
        exit(1);
    }

    return memory;
}

void file_to_matrix(FILE *path_matr, matr *m) {
    long **matrix = (long**) emalloc(SIZE * sizeof(long*));
    for (int i = 0; i < SIZE; i++) matrix[i] = (long*) emalloc(SIZE * sizeof(long));

    char line[4];
    fscanf(path_matr, " %[^\n]", line);

    // This code does not …
Run Code Online (Sandbox Code Playgroud)

c segmentation-fault

2
推荐指数
1
解决办法
115
查看次数

是否可以在Python 2中使用'print >>'而不使用换行符和空格?

在以下代码中:

with open("output", "w") as f:
    print >> f, "foo"
    print >> f, "bar"
Run Code Online (Sandbox Code Playgroud)

'output'文件将是:

foo
bar
Run Code Online (Sandbox Code Playgroud)

如何避免使用换行符和空格print >>

PS:我其实想知道是否可以使用它print >>.我知道其他方法可以避免'\n',例如f.write("foo")f.write("bar").

另外,我知道尾随的逗号.但那打印foo bar,而不是foobar.

python python-2.x python-2.7

2
推荐指数
1
解决办法
440
查看次数

标签 统计

c ×1

c++ ×1

fflush ×1

iostream ×1

python ×1

python-2.7 ×1

python-2.x ×1

segmentation-fault ×1

stdio ×1