gpt4 book ai didi

c++ - 如何在 C++ 中正确使用没有输入参数的 void 函数

转载 作者:行者123 更新时间:2023-11-30 05:05:19 25 4
gpt4 key购买 nike

我是 C++ 的新手。我需要制作一个小应用程序来读取 txt 文件的内容,然后在控制台中显示内容。我有三个点形成一个三角形,稍后我将绘制它。我想在一个名为 read2dFile 的函数中完成所有这些操作,所以我的 main 实际上是空的(除了函数的调用)。当我在另一个项目的主程序中尝试这段代码时,一切正常。好像我的功能没有正确声明。这是我的代码:

**Test.cpp** (FOR THE MAIN)

// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "read2dFile.h"

int main()
{
read2dFile();
return 0;
}

read2dfile.h(用于函数头文件)

#ifndef READ2DFILE_H_
#define READ2DFILE_H_

#include <iostream>
#include <iomanip>
#include <array>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>

using namespace std;

void read2dFile();

#endif

read2dFile.cpp(用于函数代码)

#include "read2dFile.h"

int row = 0;
int col = 0;

void read2dFile() {

string line;
int x;
int array[100][100] = { { 0 } };
string filename;

ifstream fileIN;

// Intro
cout
<< "This program reads the number of rows and columns in your data
file."
<< endl;
cout << "It inputs the data file into an array as well." << endl;
cout << "\nPlease enter the data file below and press enter." << endl;
cin >> filename;

fileIN.open(filename);

// Error check
if (fileIN.fail()) {
cerr << "* File you are trying to access cannot be found or opened *";
exit(1);
}

// Reading the data file
cout << "\n" << endl;
while (fileIN.good()) {
while (getline(fileIN, line)) {
istringstream stream(line);
col = 0;
while (stream >> x) {
array[row][col] = x;
col++;
}
row++;
}
}

// Display the data
cout << "# of rows ---> " << row << endl;
cout << "# of columns ---> " << col << endl;
cout << " " << endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << left << setw(6) << array[i][j] << " ";
}
cout << endl;
}

}

最佳答案

我有一些建议(您的代码对我来说编译得很好)。

  1. 不是针对您的问题,但您应该了解object oriented programming让 C++ 的生活更轻松。
  2. 这些是您的read2dFile() 函数需要的唯一包含文件。将它们放入 read2dFile.cpp 中!原因是因为除非绝对必要,否则您不希望 header 包含在其他 header 中。

这些指令将位于 read2dFile.cpp

的顶部
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
  1. using namespace std; 打开闸门并可能导致命名空间冲突。尽量避免这样做。如果您确实坚持这样做,请在 .cpp 源文件中(而不是在您的 .h 头文件中)执行。相反,您可以声明使用标准命名空间的特定部分(仅您需要的部分)。

这些 using 指令可以代替您的 using namespace std; 并且您将再次将它们放入 read2dFile.cpp 源文件.

using std::string;
using std::ifstream;
using std::cout;
using std::endl;
using std::cin;
using std::cerr;
using std::istringstream;
using std::left;
using std::setw;
  1. 您的 read2dFile.h 现在已缩减为您的函数声明。

文件现在看起来像这样。

#ifndef READ2DFILE_H_
#define READ2DFILE_H_

void read2dFile();

#endif

您的 main() 可以保持原样,如果它仍然不适合您,请尝试从中删除预编译头指令 #include "stdafx.h"您的 Test.cpp 源文件。这里不需要它,有时在某些情况下会导致编译器错误。

关于c++ - 如何在 C++ 中正确使用没有输入参数的 void 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48455168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com