如何在C ++中“打印”字符串数组?

Ein*_*ler -2 c++ arrays string printf

基本上,我有以下代码:

#include <stdio.h>
#include <string>
#include <iostream>

using namespace std;

int main(void)
{
   string energy[9] ={"1E4","3E4","1E5","3E5","1E6","3E6","1E7","3E7","1E8"};

   for (int j = 0; j < 9; j++)
   {
     //printf("%s\n", energy[j]);
     //cout << energy[j] << endl;
   }
}
Run Code Online (Sandbox Code Playgroud)

我想用printf来“打印”字符串数组的每个元素,就像“ cout”命令一样。我已经尝试过指向数组第一个元素的指针和其他一些技术,但是我无法使其工作。我需要在printf中添加什么,为什么我的printf中当前不可用?

在此先感谢您的帮助。

Ven*_*nor 5

printf期望char*类型,但是您要传入std::string。使用data()c_str()函数从字符串中提取基础char数组指针。

printf("%s\n", energy[j].data());
Run Code Online (Sandbox Code Playgroud)