我正在学习用C ++编写代码,并且正在努力打开文件并让我的代码在字符串或数组内复制文件的内容。 (不要考虑cin的行,这只是一个测试,看看代码是否已进入并且现在就可以了。我这样做是为了手动插入文件中显示的值,但是我希望我的代码手动完成操作,我需要指针吗?我无法处理它们。另外,我在CLion上进行编码,因此配置令人困惑,有人一直在说我需要将文件放在c-make-build-debug文件夹中,但如果这样做,则不会直接打开该文件。 这也和(int argc,char*argv[])
有关吗? (对我来说含义模糊的行)
#include <cstdio>
#include <cstring>
#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();
}
该练习的目的是从文件中获取信息,然后将它们重写为可以与其他字符串进行比较的字符串相同的文件。
问题是我已经尝试通过getline(apri,riga)这样做,然后试图将riga的内容复制到另一个字符串中,但它确实不行。购物清单包含单词和浮点数,所以我考虑分析文件的每一行并将每个部分放入它专用的字符串/数组,但我不知道该如何做不是指定的尺寸– 28分钟前AvengerScarlet
好,让我们先解决一个问题。首先,如何将参数传递给代码-不必这样做,但这是您的问题之一:
这也与(int argc,char * argv [])有关吗? (其含义是对我不了解)
#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;
}
假设您有这样的购物清单:shoppinglist.txt包含:
Stacks of Toilet paper
Oil
Bunch of noodlesShopping List:
Stacks of Toilet paper
Oil
Bunch of noodles
Hand sanitizer
...
此代码可以正常运行,您可以执行它。 C:/program.exe c:/shoppinglist.txt
取决于您使用它编译的名称和位置解决有关argv和读取文件的问题
我仍在研究此答案的下一部分,这是第一部分-如果需要更多解释,请留下评论。