2016-02-15 26 views
-2

我试图从给定的txt文件在linux终端中创建用户。每行的格式在文本文件中是“Josh:0001”。 Josh是用户名,0001是密码。我可以为每一行创建一个字符串,但我无法弄清楚如何将字符串拆分为“:”字符。从文本文件中添加linus用户的C++程序

#include <iostream> 
#include <cstdlib> 
#include <string> 
#include <sstream> 
#include <fstream> 
using namespace std; 

int main() 
{ 
cout << "Hello World" << endl; 
//system("mkdir user1"); 


string anyCommand="", name, userpassword; 


//code to open a file 
string users[120]; 
string line; 
//int userCount=0; 
ifstream myfile ("users.txt"); 
if (myfile.is_open()) 
{ 

for(int i = 0; i < 1; i++) 
{ 
    //code to read a user from the input file 
    getline(myfile,line); 
    stringstream temp(line); 




    name += temp.str(); 


    //useradd vs. userdel 
    anyCommand = "useradd " + name ; 

    cout << anyCommand << endl; 
    system(anyCommand.c_str()); 

    //anyCommand = ""; 
    //userpassword = "sosu-2014"; 
    //set the command, e.g., system("echo john:sosu-2014 | chpasswd"); 
    anyCommand = "echo " + name + ":" + userpassword + " | chpasswd"; 
    cout << anyCommand << endl; 
    system(anyCommand.c_str()); 

}} 

//code to close a file 
cout << "Job Done!" << endl; 

return 0; 
} 

对不起,我注释掉了一些东西,尝试不同的方法。

+1

[使用getline和while循环来分割字符串]可能的重复(http://stackoverflow.com/questions/5757721/use-getline-and-while-loop-to-split-a-string) – LogicStuff

+0

Don不要为这个烂摊子道歉;解决这个烂摊子。 –

回答

0

要分割字符串,请使用std :: string中的find_first_of(或find_last_of)和substr函数。

+0

我还是不明白这一点..我知道非常基本的代码,我的字符串没有任何空格。 – turboz8607

相关问题