我正在学习使用C++编写代码,并且正在努力打开文件并让我的代码在字符串或数组内复制文件的内容。 (不要考虑cin的行,这只是一个测试,看看代码是否已进入并且现在就可以了。我这样做是为了手动插入文件中显示的值,但是我希望我的代码手动完成操作,我需要指针吗?我无法处理它们。
另外,我在CLion上编写代码,配置太困惑了,有人一直在说我需要将文件放在c-make-build-debug文件夹中,但是如果这样做,文件将无法直接打开。
这也和(int argc,char*argv[])有关吗? (对我来说含义模糊的行)

   // #include <cstdio>  not needed
   // #include <cstring> not needed
    #include <fstream>
    #include <iostream>


    using namespace std;

    int main(int argc,char *argv[])
    {
     string riga;
     string row;
    char prodotto[26];
    int numero [100];
    float prezzo [6];
    float datoprezzo;
    int datonumero;
    char cliente[26];
    ifstream apri;
    ofstream chiudi;
    apri.open(argv[1]);
    if(!apri.is_open())
    {
      cerr << "File non aperto correttamente." << endl;
    }
    if(apri.is_open())
    {
     while(getline(apri,riga))
     {
       cout << riga << endl;
       cin >> prodotto;
       cin >> datonumero;
       cin >> datoprezzo;
       cin >> cliente;
       }

    }
    apri.close();

   }

最佳答案



好的,让我们先解决一个问题。首先,如何将参数传递给代码-不必这样做,但这是您的问题之一:



#include <fstream>
#include <iostream>
using namespace std;
int main (int argc, char *argv[])
{
   // argc should be 2 for correct execution, the program name
   // and the filename
   if ( argc != 2 )
   {
      // when printing out usage instructions, you can use
      // argv[ 0 ] as the file name
      cout << "usage: " << argv[ 0 ] << " <filename>" << endl;
   }
   else
   {
      // We assume argv[ 1 ] is a filename to open
      ifstream the_file( argv[ 1 ] );
      // Always check to see if file opening succeeded
      if ( ! the_file.is_open() )
      {
         cout << "Could not open file " << argv[ 1 ] << endl;
         return 1;
      }
         char x;
         // the_file.get( x ) reads the next character from the file
         // into x, and returns false if the end of the file is hit
         // or if an error occurs
         while ( the_file.get( x ) )
            {
               cout << x;
            }
   } // the_file is closed implicitly here by its destructor
   return 0;
}

假设您有一个真实的实时购物 list ,如下所示:
shoppinglist.txt包含:
Stacks of Toilet paper
Oil
Bunch of noodlesS
Hand sanitizer
...

该代码可以正常工作,您可以执行使用C:/program.exe c:/shoppinglist.txt,具体取决于您编译时使用的名称和位置
解决有关argv和读取文件的问题

第2部分





不,仅当您使用参数(* argv ...)时,因为这是(必须)是一个指针或一个指针的指针

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}
[file example.txt]
Writing this to a file.

第三部分




有很多解决方案,我将首先尝试从提供了一个char的那个方法转换为这里描述的字符串。
https://www.techiedelight.com/convert-char-to-string-cpp/

我想这不是为了给您答案而编写整个程序的目的-我已经结束了这篇文章,等待对这篇文章的评论,看看您对我提供的帮助有多远。

09-08 00:26
查看更多