【问题标题】:Output for the matrix A is overlapped with the Matrix B矩阵 A 的输出与矩阵 B 重叠
【发布时间】:2018-10-19 14:33:39
【问题描述】:

所以,这是从 txt 文件中读取矩阵 A 和 B 的代码。我发现的以下代码能够读取这两个文件。但是,矩阵 A 的输出与矩阵 B 重叠(下图) enter image description here

Matrix A -----
1       2       3
4       5       6
7       8       99 

Matrix B -----
0       1       1
2       0       0
2       0       00 

那么,如何避免它重叠,请帮助:)

#include<iostream>
#include<fstream>
using namespace std;

int main()
{

    {   
        char ch;
        const char *fileName="MatrixA.txt";     // FOR MATRIX A

        ifstream file;

            file.open(fileName,ios::in);
                if(!file)
                {
                    cout<<"Error in opening file!!!"<<endl;
                    return -1; 
                }


                while (!file.eof()) 
                {
                    file >> noskipws >> ch; 
                    cout << ch; 
                }

        file.close();
    }

    {
        char ch;
        const char *fileName="MatrixB.txt";     // FOR MATRIX A

        ifstream file;

            file.open(fileName,ios::in);
                if(!file)
                {
                    cout<<"Error in opening file!!!"<<endl;
                    return -1; 
                }


                while (!file.eof()) 
                {
                    file >> noskipws >> ch; 
                    cout << ch; 
                }

        file.close();
    }


    return 0;
}

编辑:谢谢大家!修复了它,是的,我知道这不是读取矩阵的代码(对不起,错误信息)。我只是想让它看起来像一个,呵呵,再次感谢

【问题讨论】:

  • 在两者之间使用std::cout &lt;&lt; std::endl ?
  • 编译所有警告和调试信息,所以g++ -Wall -Wextra -gGCC。改进您的代码以获得没有警告。 使用调试器e.g. gdb 了解程序的行为。改进并重复直到满意为止
  • 不要复制粘贴代码(你不修复复制代码的注释),而是创建函数。
  • @Jarod42 std::endl 不等于换行符,因为它会刷新
  • @Gladaed:这对初学者来说“更好”(之前的(调试)输出在崩溃之前打印,这有助于定位错误)。

标签: c++ fstream iostream


【解决方案1】:

您刚刚打印了两个文件的逐个字符副本,它们之间没有任何内容。显然“MatrixA.txt”文件末尾没有换行符。

您可以在第一个文件的输出后添加一个'\n' 字符。

std::cout << '\n';

实际上,您没有读取两个矩阵,因为您没有使用文件中存在的任何算术值。如果您想这样做,您首先必须在程序中提出Matrix 的一些表示,然后才能考虑从文件中读取它。

【讨论】:

    猜你喜欢
    • 2017-04-20
    • 2017-09-26
    • 2013-04-20
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多