【问题标题】:Troubles trying to convert string to char[][]尝试将字符串转换为 char[][] 时出现问题
【发布时间】:2022-01-08 22:44:13
【问题描述】:

我正在构建一个名为 Board 的类,它将从 txt 文件中获取它的详细信息。

#define ROW 25;
#define COL 80;
class Board
{
    char _board[ROW][COL] = {0};

public:
    Board(string name); // our new constructor - reads map from file.
};

它接收字符串名称,并尝试打开具有特定名称的文件。 如果我们确实在正确的文件中,我想从中读取字符,并将它们复制到板上。 我一直在尝试几件事,总结在这段代码中:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
    Board::Board(string name)
{
    string line;
        ifstream file(name);
        int i = 0;
    if (file.is_open())
        {
            while (!file.eof())
            {
    
            (1) getline(file, line);
            (2) const char* test = line.c_str();
            (3) strcpy_s(_board[i], test);

        (4) _board[i] = line;

                    i++;

            }
// MORE FUNCTIONS NOT RELEVANT TO THIS QUESTION
        }
}

我收到以下错误: 对于 (3):程序崩溃。 对于 (4):表达式必须是可修改的左值。 对于(1),(2):测试和线路工作良好。

有没有其他更简单的方法可以将字符串复制到 char* 而不使用丑陋的循环,并复制每个字符? 为什么 (3) 会导致我的程序崩溃?

提前致谢!

【问题讨论】:

标签: c++ string char


【解决方案1】:

不相关,但 void main() 已被弃用多年且在当前版本的标准中不正确:应为 int main()...

下一个while (!file.eof()) 是一个常见但可怕的事情:eof 只有在读取操作没有返回任何内容后才变为真。这意味着您将处理最后一行两次...

对于您的错误:

  • (4) _board[i] 是一个数组,一个数组不能在赋值的左边(惯用语:它不是一个左值

  • (3):strcpy_s 不是替代strcpy 并且您的编译器应该发出警告(任何正确编译器都会发出.. .)。应该是:

      strcpy_s(_board[i], COL, test);
    

【讨论】:

  • 感谢您的评论。我已经更新了循环条件,但是 strcpy_s(_board[i], COL, test) 使我的程序崩溃了。即使在使用 strcpy 时,我也会收到 CRT_SECURE 警告,即使我在页面开头定义它也是如此。
【解决方案2】:
#include <iostream>
#include <fstream>
#include <string>
#define ROW 25;
#define COL 80;
int i=0;
class Board
{
    char _board[ROW][COL] = {0};

public:
    Board(string name); // our new constructor - reads map from file.
};
Board::Board(string name)
{
   fstream newfile;

   newfile.open(name,ios::in); 

   if (newfile.is_open()){   

      string tp;
      while(getline(newfile, tp)){ 
        strcpy(_board[i], tp);
        i++;
      }
      newfile.close(); 
   }
}

【讨论】:

  • 对于此代码,我收到以下错误:“不存在从 std::string 到 const char * 的合适转换函数”。有没有我可能遗漏的内容?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 2020-03-17
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
相关资源
最近更新 更多