Solve the problem arising when using the getline} {freopen read a different file

Read a single file

Use freopen redirection.

Getline progressive reading process.

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
string s;

int main()
{
    freopen("text1.in", "r", stdin);
    while (getline(cin, s)) {
        /* - code - */
    }
    fclose(stdin);
    return 0;
}

Read multiple files

The basic method above.

Special Note: In a file has been read,

Use cin.clear () clear input stream.

There may be a first file, other files without phenomenon except read.

2020-1-27-1: 07 generates the read processing problems when two txt text data.

编译环境:
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=e:/tio/dev-cpp/mingw32/bin/../libexec/gcc/mingw32/4.8.1/lto-wrapper.exe
Target: mingw32
Configured with: ../gcc-4.8.1/configure --prefix=/mingw --host=mingw32 --build=mingw32 --without-pic --enable-shared --enable-static --with-gnu-ld --enable-lto --enable-libssp --disable-multilib --enable-languages=c,c++,fortran,objc,obj-c++,ada --disable-sjlj-exceptions --with-dwarf2 --disable-win32-registry --enable-libstdcxx-debug --enable-version-specific-runtime-libs --with-gmp=/usr/src/pkg/gmp-5.1.2-1-mingw32-src/bld --with-mpc=/usr/src/pkg/mpc-1.0.1-1-mingw32-src/bld --with-mpfr= --with-system-zlib --with-gnu-as --enable-decimal-float=yes --enable-libgomp --enable-threads --with-libiconv-prefix=/mingw32 --with-libintl-prefix=/mingw --disable-bootstrap LDFLAGS=-s CFLAGS=-D_USE_32BIT_TIME_T
Thread model: win32
gcc version 4.8.1 (GCC)

Compile command:
G ++ Name.cpp -o name.exe

Right:

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
string s;

int main()
{
    freopen("text1.in", "r", stdin);
    while (getline(cin, s)) {
        /* - code - */
    }
    fclose(stdin);
    cin.clear();
    freopen("text2.in", "r", stdin);
    while(getline(cin, s)) {
        /* - code - */
    }
    fclose(stdin);
    // ...
    return 0;
}

Guess you like

Origin www.cnblogs.com/leprechaun-kdl/p/12235322.html
Recommended