プロジェクトオイラープログラムであるにもかかわらず、次のコードは実際にはそれほど関係ありません。100桁の数字を50個追加したいのですが、各数字の各桁を配列addends[100][50]の要素に割り当てています。次に、各桁/場所を個別に合計し、余分な桁を繰り越します。番号は、という名前のテキストファイルから読み込まれ、Input.txt
すべての番号が含まれているだけです。http://projecteuler.net/problem=13
string numbers[100][50]
ファイル入力ストリーム()から文字列配列()の要素に文字を割り当てるのに問題があります<fstream>
。問題はコメントでより完全に説明されています:
"[最初のループの場合]このループは、文字列配列内のすべての文字列に番号を割り当てます。2番目の番号(50)は何もしませんが(std :: stringによってオーバーライドされるようです。変数宣言を参照)、ループが機能するためにはそこにある必要があります。ループの場合も同じ「ロジック」です。「j」は何もしませんが、ループが機能するためにはそこにある必要がありますか?」
また、(2番目のループの場合)「このループは、対応する文字列配列要素から「addends [100][50]」配列を埋めます。配列「numbers[i]」を使用して「char_to_int()」を呼び出そうとすると[j] "、コンパイラは入力が正しいデータ型ではないと文句を言います。変数" k "を追加すると、ループは1回の実行で機能しますが、最終的に2番目のループでクラッシュします(" numbers [i] [j ] [k] ")。そこで" char_to_int((numbers [i] [j])。c_str()) "を試しましたが、コンパイラは" constchar*"が"char"と互換性がないと文句を言います。ポインタを追加すると解決します問題( "char_to_int(*((numbers [i] [j])。c_str()))")ですが、プログラムは後でクラッシュします。 " 読みやすくするために重要ではないコードをいくつか取り出しました。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int char_to_int(char chInput);
int main()
{
int placeholder; //so console doesn't close immediately upon finish
int sum[102] = {0}; // 100+2, 100 places + 2 places from carrying over
int addends[100][50] = {0};
string numbers[100][50];
ifstream input("Input.txt");
/* This loop assigns a number to every string in the string array. Even
* though the second number (50) doesn't do anything (it seems to be
* overridden by std::string; see variable declaration), it needs to be
* there for the loop to work. Same "logic" for the loop; "j" doesn't do
* anything but needs to be there??? Confused :-\
*/
for (int i = 0; i < 100; i++)
for (int j = 0; j < 1; j++)
getline(input, numbers[i][j]);
/* This loop fills in the "addends[100][50]" array from the corresponding
* string array element. If I try to call "char_to_int()" with the array
* "numbers[i][j]", the compliler complains that the input isn't of the
* right data type. Adding a variable "k" makes the loop work for one run,
* but eventually crashes on the second loop (using "numbers[i][j][k]").
* So I tried "char_to_int((numbers[i][j]).c_str())", but the compiler
* complains that "const char *" is incompatible with "char". Adding a
* pointer resolves the issue ("char_to_int( *( (numbers[i][j]).c_str() ) )"),
* but the program still crashes on the second loop through.
*/
for (int i = 0; i < 100; i++)
for (int j = 0; j < 50; j++)
for (int k = 0; k < 1; k++) //used when the variable "k" was being used
addends[i][j] = char_to_int( (numbers[i][j]).c_str() );
return 0;
}
コードは完成していません。私は(明らかに)これを最初に修正する必要があるので、続行しないことにしました。